@@ -91,9 +91,26 @@ export const initializeTraefik = async ({
9191 try {
9292 const service = docker . getService ( "dokploy-traefik" ) ;
9393 await service ?. remove ( { force : true } ) ;
94- await new Promise ( ( resolve ) => setTimeout ( resolve , 5000 ) ) ;
95- } catch ( _ ) { }
9694
95+ let attempts = 0 ;
96+ const maxAttempts = 5 ;
97+ while ( attempts < maxAttempts ) {
98+ try {
99+ await docker . listServices ( {
100+ filters : { name : [ "dokploy-traefik" ] } ,
101+ } ) ;
102+ console . log ( "Waiting for service cleanup..." ) ;
103+ await new Promise ( ( resolve ) => setTimeout ( resolve , 5000 ) ) ;
104+ attempts ++ ;
105+ } catch ( e ) {
106+ break ;
107+ }
108+ }
109+ } catch ( err ) {
110+ console . log ( "No existing service to remove" ) ;
111+ }
112+
113+ // Then try to remove any existing container
97114 const container = docker . getContainer ( containerName ) ;
98115 try {
99116 const inspect = await container . inspect ( ) ;
@@ -103,15 +120,31 @@ export const initializeTraefik = async ({
103120 }
104121
105122 await container . remove ( { force : true } ) ;
123+ await new Promise ( ( resolve ) => setTimeout ( resolve , 5000 ) ) ;
106124 } catch ( error ) {
107- console . log ( error ) ;
125+ console . log ( "No existing container to remove" ) ;
108126 }
109127
110- await docker . createContainer ( settings ) ;
111- const newContainer = docker . getContainer ( containerName ) ;
112- await newContainer . start ( ) ;
128+ // Create and start the new container
129+ try {
130+ await docker . createContainer ( settings ) ;
131+ const newContainer = docker . getContainer ( containerName ) ;
132+ await newContainer . start ( ) ;
133+ console . log ( "Traefik container started successfully" ) ;
134+ } catch ( error : any ) {
135+ if ( error ?. json ?. message ?. includes ( "port is already allocated" ) ) {
136+ console . log ( "Ports still in use, waiting longer for cleanup..." ) ;
137+ await new Promise ( ( resolve ) => setTimeout ( resolve , 10000 ) ) ;
138+ // Try one more time
139+ await docker . createContainer ( settings ) ;
140+ const newContainer = docker . getContainer ( containerName ) ;
141+ await newContainer . start ( ) ;
142+ console . log ( "Traefik container started successfully after retry" ) ;
143+ }
144+ }
113145 } catch ( error ) {
114- console . log ( error ) ;
146+ console . error ( "Failed to initialize Traefik:" , error ) ;
147+ throw error ;
115148 }
116149} ;
117150
0 commit comments