如何通过Dockerode判断Docker容器已启动并运行?
Great question! When using Dockerode's run method, the default callback actually fires after the container exits—which isn't what you need if you want to run actions once the container is up and running. Here are a few reliable approaches to handle this:
1. Listen to the Container's start Event
The run method returns a Container instance, which emits a start event as soon as the container is started. You can hook into this event to trigger your post-start actions:
// Start the container const container = docker.run('imageName', [], process.stdout, function(err, data, container) { if (err) { console.log("Error while starting docker", err); } // Note: This callback runs when the container EXITS, not when it starts }); // Listen for the 'start' event to know when the container is running container.on('start', () => { console.log("Container is now in running state!"); // Execute your post-start operations here // Example: Run a command inside the container, update logs, etc. });
2. Poll the Container's Status (Reliable for Edge Cases)
If event listeners feel inconsistent (e.g., due to Docker daemon delays), you can actively poll the container's status using inspect() until it shows as running:
// Helper function to wait for the container to be running const waitForContainerRunning = async (container) => { const checkStatus = async () => { const containerInfo = await container.inspect(); if (containerInfo.State.Status === 'running') { return; } // Wait 500ms before checking again await new Promise(resolve => setTimeout(resolve, 500)); await checkStatus(); }; await checkStatus(); console.log("Container is confirmed running!"); // Run your post-start actions here }; // Start the container const container = docker.run('imageName', [], process.stdout, function(err) { if (err) { console.log("Error while starting docker", err); } }); // Trigger the status check waitForContainerRunning(container);
3. Use Detached Mode (For Non-Blocking Execution)
If you don't need to stream the container's output indefinitely, you can start the container in detached mode. This makes the run callback fire immediately after the container is created and started, then you can verify its status:
docker.run('imageName', [], process.stdout, { Detach: true }, async function(err, data, container) { if (err) { console.log("Error while starting docker", err); return; } // Wait for the container to reach running state await waitForContainerRunning(container); // Execute your post-start tasks here }); // Reuse the same waitForContainerRunning helper from approach 2 const waitForContainerRunning = async (container) => { let containerInfo; do { containerInfo = await container.inspect(); await new Promise(resolve => setTimeout(resolve, 500)); } while (containerInfo.State.Status !== 'running'); };
Key Notes:
- Always wrap async operations like
inspect()in try/catch blocks to handle potential errors and avoid unhandled promise rejections. - Adjust the polling interval (500ms in examples) based on your needs—shorter intervals mean faster detection but slightly more resource usage.
内容的提问来源于stack exchange,提问作者Ankit Arora

