Use docker compose wait with specific services
In the previous step, we used docker compose wait
to wait for all services to stop. In this step, we will learn how to use docker compose wait
to wait for specific services to reach a certain state.
First, let's start our services again using docker-compose up -d
. Make sure you are in the ~/project
directory.
cd ~/project
docker-compose up -d
Verify that both services are running using docker-compose ps
.
docker-compose ps
Now, open a new terminal window or tab. We will use this new terminal to demonstrate waiting for a specific service.
In the new terminal window, navigate to the ~/project
directory.
cd ~/project
We can specify which services to wait for by providing their names after the docker compose wait
command. For example, to wait only for the web
service to stop:
docker compose wait web
Similar to the previous step, this command will block because the web
service is currently running.
Now, switch back to your original terminal window. We will stop only the web
service. To do this, we can use the docker stop
command with the container name. You can find the container name using docker ps
. It will likely be something like project-web-1
.
cd ~/project
docker stop project-web-1
Replace project-web-1
with the actual container name if it's different.
Observe the output in the original terminal window. You will see a message indicating that the web
container is being stopped.
Now, switch back to the new terminal window where you ran docker compose wait web
. As the web
service is stopped, the docker compose wait web
command will detect this and exit.
You should see the command prompt return in the new terminal window. Notice that the docker compose wait web
command exited even though the db
service is still running.
To confirm that the db
service is still running, switch back to the original terminal and run docker-compose ps
.
cd ~/project
docker-compose ps
You should see the db
service listed with the state Up
, while the web
service is no longer listed or shows a stopped state.
Finally, let's stop the remaining db
service.
cd ~/project
docker-compose down
You have successfully used docker compose wait
to block until a specific service stopped.