Keeping a Docker Container Open in Docker Compose
I wanted to run a couple of Alpine containers with Docker Compose to test out network communication between them. But the containers immediately exited after starting because there was nothing running on them.
I needed the equivalent of running docker run -it alpine but in Docker Compose.
I found two ways of doing this.
git
The first is to use stdin_open: true in the Docker Compose file. The second is to use tty: true. Both will keep the container running. Then I can attach to the container terminal to run some commands.
Here is the docker-compose.yml file I used -
1services:
2 alpineone:
3 container_name: first_container
4 image: alpine
5 stdin_open: true # this works
6
7 alpinetwo:
8 container_name: second_container
9 image: alpine
10 tty: true # this also worksRun Docker compose with -
docker compose -f docker-compose.yml up To attach to the running containers, use -
docker exec -it first_container /bin/sh
# and
docker exec -it second_container /bin/sh