Executing Docker Compose Commands
local graph
Chapter 4 — Executing Docker Compose Commands
Section titled “Chapter 4 — Executing Docker Compose Commands”In the previous chapter, we focused on using Docker networks and volumes on a Compose application. By using networks, we managed to establish connectivity between the components of a Compose application; by using volumes, we facilitated I/O operations and kept the data created portable and permanent.
So far, we have used various Docker Compose commands in order to provision our applications and interact with Compose components. This chapter will focus on the available Compose commands and their options. Once we have an overview of the available commands, we will dive into the provisioning commands and the commands interacting with the Compose containers. After that, we will learn more about cleanup commands. By covering the commands that assist in our application development, we will have a deep dive into monitoring commands.
The following main topics will be covered in this chapter:
- Introducing Compose commands
- The Docker CLI versus Compose commands
- Provisioning commands
- Container commands
- Cleanup commands
- Image commands
- Monitoring commands
- Other commands
Technical requirements
Section titled “Technical requirements”The code for the book is hosted on GitHub at https://github.com/PacktPublishing/A-Developer-s-Essential-Guide-to-Docker-Compose. If there is an update to the code, it will be updated on the GitHub repository.
Introducing Compose commands
Section titled “Introducing Compose commands”Compose has a variety of commands that can be used to interact with containers, monitor applications, and also to manage images.
Throughout this chapter, we shall examine Compose commands, apply them to a target application, break down their usage, and understand how they work behind the scenes.
The commands we will focus on are the following:
buildcreateupimagespullpushdownrmlogstoppsevents
We will learn more about these commands, see how we can benefit from them, and utilize them on a Compose application.
The Docker CLI versus Compose commands
Section titled “The Docker CLI versus Compose commands”Most of these commands seem familiar to the ones we used through the Docker CLI. The difference between the Compose and the Docker CLI commands is that the CLI commands operate through all the Docker components in your system, whereas the Compose ones are limited in the context of the Compose application specified in the docker-compose.yaml file.
Behind the scenes, the Compose command will parse the Compose file and retrieve information about the application. The API calls issued to the Docker Engine will contain filters based on the information retrieved previously and will interact only with the services and resources of the application. For example, the ps command, instead of retrieving all the running containers, which would have happened if we used the Docker CLI, will retrieve only the containers that should run on the Compose application.
Setting up the target application
Section titled “Setting up the target application”In order to make the commands showcase feasible, we will combine the work of the previous chapters and assemble a Compose application. The application should use the source code of the Task Manager application we developed in Chapter 2, Running the First Application Using Compose, along with a Redis database.
The Compose service definition uses the previous chapter’s code:
services: task-manager: build: context: ../Chapter2/. image: docker.io/library/chapter4_task-manager ports: - 8080:8080 environment: - REDIS_HOST=redis:6379 redis: image: redis ports: - 6379:6379We have a summary of the commands that we will focus on and also an application set up in order to apply those commands. In the next section, we shall focus on commands that provision resources.
Provisioning commands
Section titled “Provisioning commands”By having a Compose application file set up, we can now provision the application. The commands we will use are the following:
buildcreateup
Let’s take a look at them.
As seen previously, we do not need to build a Docker image and tag it manually before using it on Compose. Compose can build the image and use it for the application.
Issuing the build command creates the image:
$ docker compose build=> => exporting layers 0.0s...=> => naming to docker.io/library/chapter4_task manager 0.0s$ docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEchapter4_task-manager latest 58247e548811 35 hours ago 529MBBy using the build command, we create the image for the Task Manager application, and it has been tagged appropriately. We shall now proceed with getting the application up and running.
create
Section titled “create”create has been deprecated, since we can use up instead. The purpose of create was to create the containers, volumes, and networks but without starting the containers. This functionality has been replaced by up –no-start:
$ docker compose create[+] Running 3/0 Network chapter4_default Created 0.0s Container chapter4-redis-1 Created 0.0s Container chapter4-task-manager-1 Createdup has many usages and parameters. We will replace the previous create operations with up:
$ docker compose up --no-start[+] Running 3/3 Network chapter4_default Created 0.0s Container chapter4-task-manager-1 Created 0.0s Container chapter4-redis-1 Created$ docker ps -aCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES3d1ad2f353d3 redis "docker-entrypoint.s…" 3 seconds ago Created chapter4-redis-1b6d1a5f16313 chapter4_task-manager "/task_manager" 3 seconds ago Created chapter4-task-manager-1The containers and networks have been created but do not run.
Since we created the resources, we will start the application. A useful command is -d or – detach, the detached mode. The detached mode can help run the Compose application without being bound to a terminal:
$ docker compose up --detach[+] Running 2/2 Container chapter4-task-manager-1 Started 0.3s Container chapter4-redis-1 StartedAs we have previously created the resources and built the images, we will instruct up not to create the image by using --no-build:
$ docker compose up --no-build --detach[+] Running 3/3 Network chapter4_default Created 0.0s Container chapter4-redis-1 Started 0.3s Container chapter4-task-manager-1 StartedIf we need to update a service, we can update and delete the resources from old services. For example, in the case of rolling out task-manager-2, we would like the old container versions to be removed.
Let’s suppose we renamed the service as follows:
services: task-manager-2:..If we execute up, a warning shall be printed:
$ docker compose upWARN[0000] Found orphan containers ([chapter4-task-manager-2-1]) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up.We shall tackle this by using --remove-orphans:
$ docker compose up --remove-orphans[+] Running 3/0 Container chapter4-task-manager-1 Removed 0.0s Container chapter4-redis-1 CreatedWe’ve managed to get the application up and running by using the provisioning commands shown in this chapter. We can now use Compose commands to interact with the containers that the Compose services are running upon; those commands will solely be focused on interacting with containers.
Container commands
Section titled “Container commands”Container commands enable us to start, stop, and restart containers, execute commands upon them, and also kill them.
Throughout the book, we have executed commands using the Docker exec command. Docker Compose also provides this functionality. The difference is that instead of running the exec command directly to a container on Compose, we specify the service to execute upon. The command then will be routed to the service’s underlying container:
$ docker compose exec task-manager lsgo.mod go.sum main.goIf we check the existing containers, we will not see any extra containers provisioned:
$ docker ps -aCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES8e559f9bf6d1 chapter4_task-manager "/task_manager" 18 seconds ago Up 17 seconds 0.0.0.0:8080->8080/tcp chapter4-task-manager-146ca9a239557 redis "docker-entrypoint.s…" 18 seconds ago Up 17 seconds 0.0.0.0:6379->6379/tcp chapter4-redis-1run might seem similar to exec, but it differs in the fact that a new container will spin up. This makes it feasible to run a container in an environment provisioned by a Compose file. Thus, the container will have access to the volumes and networks that have been created:
$ docker compose run task-manager sh/app #On another terminal, we should inspect whether the container is running:
$ docker ps -aCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESb7920b959c98 host.docker.internal:5000/task-manager:0.1 "sh" 23 minutes ago Up 23 minutes 8080/tcp chapter4_task-manager_run_7ad8bcc01122...b575f8bcd7d3 host.docker.internal:5000/task-manager:0.1 "/task_manager" 2 hours ago Up 42 minutes 0.0.0.0:8080->8080/tcp chapter4-task-manager-1As shown, a new container called chapter4_task-manager_run_7ad8bcc01122 has been created; by exiting, the container will be stopped.
On Docker, the pause command suspends the processes of the specified container. By using pause on Compose, we pause the containers of the service specified:
$ docker compose pause task-manager[+] Running 1/0 Container chapter4-task-manager-1 Pauseddocker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES8e559f9bf6d1 chapter4_task-manager "/task_manager" 7 minutes ago Up 7 minutes (Paused) 0.0.0.0:8080->8080/tcp chapter4-task-manager-146ca9a239557 redis "docker-entrypoint.s…" 7 minutes ago Up 7 minutes 0.0.0.0:6379->6379/tcp chapter4-redis-1unpause
Section titled “unpause”Since we previously paused the task-manager container, we shall unpause the container using the unpause command:
$ docker compose unpause task-manager[+] Running 1/0 Container chapter4-task-manager-1 Unpaused 0.0s$ docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES8e559f9bf6d1 chapter4_task-manager "/task_manager" 8 minutes ago Up 8 minutes 0.0.0.0:8080->8080/tcp chapter4-task-manager-146ca9a239557 redis "docker-entrypoint.s…" 8 minutes ago Up 8 minutes 0.0.0.0:6379->6379/tcp chapter4-redis-1As expected, the container is unpaused.
start and stop
Section titled “start and stop”By using stop, we should stop running containers. start can be used to start existing containers. If a container is stopped, it will not be removed. We will shell into a container, create a file, and then stop the container. Once we start, the file should be there:
$ docker compose psNAME COMMAND SERVICE STATUS PORTSchapter4-task-manager-1 "/task_manager" task-manager running 0.0.0.0:8080->8080/tcp$ docker compose exec task-manager sh -c "echo test > text.txt"$ docker compose stop task-manager[+] Running 2/0 Container chapter4-task-manager-1 Stopped 0.1sThe container is stopped. We expect that by starting the container, the file we created previously will exist:
$ docker compose start task-manager[+] Running 1/1Container chapter4-task-manager-1 Started$ docker compose exec task-manager sh -c "cat text.txt"testrestart
Section titled “restart”restart will restart the Compose service. Even if the service is stopped, it will start:
$ docker compose restart task-manager[+] Running 1/1 Container chapter4-task-manager-1 StartedLet’s stop a service and see whether it will start:
$ docker compose stop task-manager[+] Running 1/0Container chapter4-task-manager-1 Stopped$ docker compose restart task-manager[+] Running 1/1Container chapter4-task-manager-1 Started 0.2sRegardless of the previous state of the application, the application started.
kill can be used to kill the containers of a service:
$ docker compose kill task-managercompose ps is like docker ps. The key difference is that the target of the compose ps is filtered based on the ones specified in the Compose file:
$ docker compose psNAME COMMAND SERVICE STATUS PORTSchapter4-task-manager-1 "/task_manager" task-manager running 0.0.0.0:8080->8080/tcpWe can display only the running services with the --services option:
$ docker compose ps --servicestask-managerWe can display only the container ID using --quiet:
$ docker compose ps --quiet9b612d9ed210ab96d2b340ed8840781c80288097e1af6a96ed208d6b6d1 fb42aWe can even show stopped containers – for example, if we run a command once on the task-manager service:
$ docker compose run task-manager sh/app # exitUsing ps –a, we can show the stopped container, created by the run command:
$ docker compose ps -aNAME COMMAND SERVICE STATUS PORTSchapter4-task-manager-1 "/task_manager" task-manager running 0.0.0.0:8080->8080/tcpchapter4_task-manager_run_91e7eec48f5d "sh" task-manager exited (0)In this section, we created our base Compose application. By using Compose commands, we have been able to build the application images the application required. By using commands to run the application, we also evaluated the extra options the commands offer. Then, we used Compose commands to interact with the containers spun up by running the application. We managed to execute commands to existing containers as well as to spin up containers using the environment’s existing resources. In the next section, we will cover commands that clean up the resources we provisioned using Compose.
Cleanup commands
Section titled “Cleanup commands”A common case with Docker is the various resources that are created when using it for day-to-day development. Removing images, containers, and also networks and volumes can become redundant. Compose offers a more managed way to deal with all those resources.
Let’s run the application in attached mode:
$ docker compose up[+] Running 2/0 Container chapter4-task-manager-1 Running 0.0s Container chapter4-redis-1 Running 0.0sOnce we hit Ctrl + D, we shall escape Compose, the logs will stop being displayed, and the services shall stop running:
Gracefully stopping... (press Ctrl+C again to force)[+] Running 2/2 Container chapter4-task-manager-1 Stopped 0.1s Container chapter4-redis-1 Stopped 0.1scanceledAs indicated by the messages, the application has stopped. The resources that have been provisioned are still there. We can examine that using images to see the images created, as well as ps to see containers that have been running:
$ docker compose imagesContainer Repository Tag Image Id Sizechapter4-redis-1 redis latest f16c30136ff3 107MBchapter4-task-manager-1 chapter4_task-manager latest 58247e548811 529MB$ docker compose psNAME COMMAND SERVICE STATUS PORTSchapter4-redis-1 "docker-entrypoint.s…" redis exited (0)chapter4-task-manager-1 "/task_manager" task-manager exited (2)$ docker network lsNETWORK ID NAME DRIVER SCOPE...ed28fb3286ab chapter4_default bridge localBy running docker compose up again, the same resources will be used.
However, we might want to remove those resources from our system and free some space, or perhaps the application that we have been developing is redundant. In this case, we can use docker compose down. This will remove the resources provisioned by the Compose application:
$ docker compose down[+] Running 3/2 Container chapter4-task-manager-1 Removed 0.1s Container chapter4-redis-1 Removed 0.1s Network chapter4_default Removed 0.0s$ docker compose psNAME COMMAND SERVICE STATUS PORTS$ docker network ls|grep chapter4Based on the commands run afterward, it seems that all the resources have been removed. However, there is still something that has been created while running the application, which is the images we built previously using docker compose build.
down comes with an option to remove the image that was built when running the application:
$ docker compose down --rmi local[+] Running 4/2 Container chapter4-redis-1 Removed 0.2s Container chapter4-task-manager-1 Removed 0.2s Image chapter4_task-manager Removed 0.0s Network chapter4_default Removed 0.0slocal will work for the images that have been built using the compose file and don’t have an image name. In our case, since we do have a tag, image: chapter4_task-manager:latest, we need to use the all parameter:
$ docker compose down --rmi all[+] Running 5/0 Container chapter4-task-manager-1 Removed 0.0s Container chapter4-redis-1 Removed 0.0s Image redis Removed 0.0s Image docker.io/library/chapter4_task-manager Removed 0.0s Network chapter4_default Removed 0.0sBe aware that all will also remove the locally cached image, as we can see in the preceding code.
In the previous steps, the usage of down removed all the containers. By using rm, we can remove containers individually. Let’s suppose we have the scenario of a poorly running container:
services: failed-manager: build: context: ../Chapter2/. entrypoint: ["/no-such-command"] task-manager: build: context: ../Chapter2/. image: chapter4_task-manager:latest ports: - 8080:8080 environment: - REDIS_HOST=redis:6379 redis: image: redis ports: - 6379:6379The failed-manager service will fail:
$ docker compose up -d[+] Running 3/4 Network chapter4_default Created 0.0s Container chapter4-failed-manager-1 Starting 0.5s Container chapter4-redis-1 Started 0.4s Container chapter4-task-manager-1 Started 0.4sError response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/no-such-command": stat /no-such-command: no such file or directory: unknownWe do see the error. If we use ps, we should see that one container is running and that the other container was just created:
$ docker compose psNAME COMMAND SERVICE STATUS PORTSchapter4-failed-manager-1 "/no-such-command" failed-manager created 8080/tcpchapter4-redis-1 "docker-entrypoint.s…" redis running 0.0.0.0:6379->6379/tcpchapter4-task-manager-1 "/task_manager" task-manager running 0.0.0.0:8080->8080/tcpLet’s remove the bad container:
$ docker compose rm failed-manager? Going to remove chapter4-failed-manager-1 Yes[+] Running 1/0 Container chapter4-failed-manager-1 RemovedAlternatively, we can force a removal using the -f or --force flag:
$ docker compose rm failed-manager --forceGoing to remove chapter4-failed-manager-1[+] Running 1/0 Container chapter4-failed-manager-1 RemovedBy using force, we avoided Command Prompt.
So far, after managing to run an application and interact with the containers that were created, we proceeded to stop the application, as well as to clean up the resources created, in order to make the running application feasible. One resource that has been created through the build process was the application’s image. Now, we shall dive deeper into managing images using Compose.
Image commands
Section titled “Image commands”Compose provides us with various options when using images. This makes its usage efficient, since there is no need to build images individually and use them in an application. Building images, tagging them, and also pushing them to a repository is something that can be done through Compose. This leads to development efforts being focused in one place.
List images
Section titled “List images”Our application so far has two services backed by containers. We can see the images used by the containers using the docker compose images command:
$ docker compose imagesContainer Repository Tag Image Id Sizechapter4-redis-1 redis 6.2.6 23d787aaa419 107MBchapter4-task-manager-1 chapter4_failed-manager latest 58247e548811 529MBWe can also make the output less verbose by using the --quiet option:
$ docker compose images --quiet58247e548811b8812d48467436bc07ed40b4a7d4cd8328e57234d465ef189 14a23d787aaa419ab884dd8682dca3153506f4dd00aba2ca9cd5953e94cae36b d7dPulling images
Section titled “Pulling images”By using the images command, we have been able to retrieve the images used by the Compose application. What if we changed the image? The expected outcome would be to pull the image before running. Compose provides the pull command, which should pull the image specified.
So, let’s specify another redis image:
services: redis: image: redis:6.2.6Instead of using up and pulling the image by default, we will use pull:
$ docker compose pull --ignore-pull-failures --parallel[+] Running 2/3 failed-manager Skipped 0.0s redis Pulled 1.2s task-manager Error 1.5sPulling task-manager: Error response from daemon: pull access denied for chapter4_task-manager, repository does not exist or may require 'docker login': denied: requested access to the resource is denied$ echo $?0As you can see, by issuing the pull command, we pulled the older Redis images specified. Also, because the task manager does not exist as an image in the registry and is a local one, it failed to pull. This did not block the operation; thus, the return of the command was 0. We achieved this by using the --ignore-pull-failures option. Also, by using the --parallel option, the images are pulled in parallel.
Pushing images
Section titled “Pushing images”Pushing images to a Docker registry can also be done using Compose. To show this example, we will set up a registry using Compose.
Local Docker registry on Compose
Section titled “Local Docker registry on Compose”In order to push Docker images, a registry is required. We will deploy a registry using Compose and configure our Compose application to use this registry.
Our Compose registry file is as follows:
services: registry: image: registry:2 ports: - 5000:5000The registry will run on port 5000; thus, we need to make sure this port is available on our system. Keep in mind that this is not a secure registry, so we need to edit the Docker daemon config to explicitly specify the non-secure registry.
The location of the daemon.json config varies on the three main operating systems:
- Linux:
/etc/docker/daemon.json - Windows:
C:\ProgramData\docker\config\daemon.json - macOS:
~/.docker/daemon.json
Once the file has been located, we need to add the following entry:
"insecure-registries" : [ "host.docker.internal:5000" ],After editing, the file should look like this:
{... "insecure-registries" : [ "host.docker.internal:5000" ], "builder" : {.. }}Pushing to the local registry
Section titled “Pushing to the local registry”Now, it is feasible to push the task-manager image to the local registry, although any available registry can work. Since the registry is a local one run by the Docker engine, we will point to it by using the host.docker.internal DNS:
services: task-manager: build: context: ../Chapter2/. image: host.docker.internal:5000/task-manager:0.1 ports: - 8080:8080 environment: - REDIS_HOST=redis:6379 redis: image: redis ports: - 6379:6379We can now build the image:
$ docker compose build[+] Building 2.0s (17/17) FINISHED=> [internal] load build definition from Dockerfile...=> => naming to host.docker.internal:5000/task-manager:0.1...Then we push the image:
$ docker compose push[+] Running 1/13 redis Skipped 0.0s Pushing task-manager: 98ca4aa0fc4c Pushed 15.8s... Pushing task-manager: 590efbee44c0 Pushed 15.8sWe built the images using Compose, and we also managed to push to a registry we created. We inspected the images used and pulled the new images specified in the compose file. The next section will be focused on monitoring our Compose application.
Monitoring commands
Section titled “Monitoring commands”A common case in day-to-day development is monitoring an application and ensuring it is operating properly. From an application using too many resources to an elusive bug, or even an application restarting, there are various cases of an application malfunctioning. For these cases, monitoring commands play a crucial role.
Logs provide the ability to view the logs of a Compose application running on our system. If we run the up command in detached mode, we won’t be able to see any logs:
$ docker compose up -d[+] Running 2/2 Network chapter4_default Created 0.0s Container chapter4-task-manager-1 StartedHowever, the logs do get generated from our applications; thus, we can retrieve them:
$ docker compose logschapter4-task-manager-1 | [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached....chapter4-task-manager-1 | [GIN-debug] Listening and serving HTTP on :8080What logs did was display all the logs the application produced on the terminal and exit. There is also the option of --follow. This way, we can follow the log output and have all new logs printed on our screen:
$ docker compose logs -fchapter4-task-manager-1 | [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached....chapter4-task-manager-1 | [GIN-debug] Listening and serving HTTP on :8080Apart from that, there are options such as --no-color, where no color is used on the terminal; --timestamps, which displays a timestamp of the log when captured; and --tail, which limits the logs displayed from each container:
$ docker compose logs -f --timestamps --tail="3" --no-colorchapter4-task-manager-1 | 2022-03-26T07:50:13.846624301Z [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.chapter4-task-manager-1 | 2022-03-26T07:50:13.846625967Z Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.chapter4-task-manager-1 | 2022-03-26T07:50:13.846627551Z [GIN-debug] Listening and serving HTTP on :8080logs is indeed a useful command, but it is limited only to the logs and the log messages that an application emits. By using top, we display the running Compose processes for the file present:
$ docker compose topchapter4-task-manager-1UID PID PPID C STIME TTY TIME CMDroot 7913 7887 0 07:50 ? 00:00:00 /task_managertop on Docker is limited to the container specified. When using top on Compose, it will monitor the containers listed in the docker-compose.yaml file.
Events
Section titled “Events”events is a functionality of Compose similar to the events command that Docker provides. By running the events command, we listen for events that happen on the Compose application:
$ docker compose events...Let’s stop the container:
$ docker stop chapter4-task-manager-1chapter4-task-manager-1On the events tab, we should see the deletion:
$ docker compose events...2022-03-26 10:05:45.233256 container stop 2cda5390558dc9d6b12bae95d6c65b23a6d95b36a5279677834f81af1d62 69f2 (name=chapter4-task-manager-1, com.packtpub.compose.app =task-manager, image=host.docker.internal:5000/task-manager:0.1)Every operation that produces Docker events commands and affects the components of our application will be printed on the screen.
We just covered monitoring commands; thus, we are now able to track events of our application, identify the resources being used, as well as to troubleshoot application issues using logs.
Other commands
Section titled “Other commands”There are commands that can help in printing the available information.
help is a terminal command that provides usage instructions for commands available.
version
Section titled “version”As seen in previous chapters, version displays the currently running version of Compose:
$ docker compose versionDocker Compose version v2.2.3port prints the port for a binding:
$ docker compose port task-manager 80800.0.0.0:8080config
Section titled “config”config is used to validate the Compose configuration and instruct information to print:
$ docker-compose configservices: redis: image: redis ports: - published: 6379 target: 6379 task-manager: build: context: /path/to/Chapter2 environment: REDIS_HOST: redis:6379 image: host.docker.internal:5000/task-manager:0.1 ports: - published: 8080 target: 8080version: '3.9'It can also be used to display only the services:
$ docker-compose config --servicestask-managerredisAlternatively, it can display the volumes specified:
$ docker-compose config --volumesBy using the preceding commands and learning more about their usage, we now have a complete overview of Compose commands that are useful on a day-to-day basis.
Summary
Section titled “Summary”In this chapter, we had an extensive look at the available Compose commands and their options. We used commands that helped us to provision our multi-container application, as well as commands that assist us to interact with the containers of our application. Thanks to the image functionalities Compose provides, we pulled, built, and deployed images to a Docker registry without issuing any non-Compose commands. By managing to run our applications and evaluate the existing command options, we also proceeded to monitor our application, either by monitoring the logs or listening to Docker events, and we even monitored the activity of our Compose processors using top.
The following chapters will move on to more specific concepts of Compose that can benefit our daily development. We will transition to a microservice-based application using Compose, and monitor it, modularize it, and build it using CI/CD.