Mastering Docker Compose: Essential CLI Commands ( part 6 )

Mastering Docker Compose: Essential CLI Commands ( part 6 )

In the previous article, we discussed the use cases and benefits of Docker Compose and multi-container applications. In this article, we will continue our discussion of Docker Compose commands.

In the previous article, we covered five Docker Compose commands: **docker-compose up** , docker-compose down , **docker-compose stop** , docker-compose start , and **docker-compose restart** .

In this article, we will discuss the remaining commands in great detail so that you can become a Docker hero from scratch. Let's get started!

docker-compose pause & docker-compose unpause

https://media4.giphy.com/media/StKiS6x698JAl9d6cx/giphy.gif?cid=7941fdc68ha8f4sb2eugku7ijnj9lnmg0ehxbg67xt8pxrhx&ep=v1_gifs_trending&rid=giphy.gif&ct=g

The docker-compose pause command is used to pause one or more containers in a Docker Compose project. When a container is paused, it will stop responding to any new requests, but its state and configuration will be preserved.

Here is an example of how to use docker-compose pause:

Let's say we have a simple Docker Compose file named docker-compose.yml with two services: a Redis database and a Node.js application that depends on Redis.

version: "3"
services:
  redis:
    image: redis:alpine
  app:
    build: .
    environment:
      - REDIS_HOST=redis
    depends_on:
      - redis
    ports:
      - "3000:3000"

To pause the Redis container, we can run the following command:

docker-compose pause redis

This will pause the Redis container, and any new requests to the Redis service will fail until it is resumed.

To resume the Redis container, we can run the following command:

docker-compose unpause redis

This will resume the Redis container, and it will start responding to new requests again.

Note that docker-compose pause and docker-compose unpause can be used with multiple container names as arguments, allowing you to pause and unpause multiple containers at once.

docker-compose ps

https://media1.giphy.com/media/1Fm7jEapE18HwS6fkT/giphy.gif?cid=7941fdc68ha8f4sb2eugku7ijnj9lnmg0ehxbg67xt8pxrhx&ep=v1_gifs_trending&rid=giphy.gif&ct=g

The docker-compose ps command is used to display the status of containers defined in the Compose file. It lists all the containers that are created based on the services defined in the docker-compose.yml file along with their status, ports, and names.

The basic syntax of the docker-compose ps command is:

docker-compose ps [options] [SERVICE...]

Here, SERVICE is an optional argument that allows you to filter the output by specifying the name of the service. If you don't specify any service name, it will show the status of all the services defined in the docker-compose.yml file.

Some commonly used options with the docker-compose ps command are:

  • q, --quiet: Only display container IDs.
  • -services: Display only service names.
  • -filter: Filter services by a property.

Here's an example of using the docker-compose ps command:

Suppose we have a docker-compose.yml file that defines three services: web, db, and redis.

version: '3'
services:
  web:
    image: nginx:latest
    ports:
      - "8080:80"
  db:
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: password
  redis:
    image: redis:latest

To display the status of all the containers defined in this file, we can run the following command:

docker-compose ps

This will output the status of all three services like this:

Name                   Command               State            Ports
-------------------------------------------------------------------------------
compose_db_1   docker-entrypoint.sh mysqld      Up      3306/tcp, 33060/tcp
compose_redis_1 /usr/local/bin/docker-entr ...   Up      6379/tcp
compose_web_1   nginx -g daemon off;             Up      0.0.0.0:8080->80/tcp

Here, we can see the status of all three services, their names, and their respective ports.

docker-compose logs

https://media0.giphy.com/media/lQO3dG0scKkkRAY5GN/giphy.gif?cid=7941fdc64h3o8ksyium0od3a6a6f17nsqhyzm5vt0mdj2eyl&ep=v1_gifs_search&rid=giphy.gif&ct=g

The docker-compose logs command is used to display the logs of services running inside the Docker Compose environment. It can be used to view the output of all the services or specific services, and provides options to display timestamps, tail logs and limit the number of lines displayed.

The basic syntax for using the docker-compose logs command is:

docker-compose logs [options] [service...]

Here are some of the commonly used options for docker-compose logs:

  • -follow, f: Follow the logs in real-time like tail -f.
  • -timestamps, t: Display timestamps along with the log lines.
  • -tail: Number of lines to display from the end of the logs. For example, -tail 50 will display the last 50 lines.
  • -no-color: Disable colored output

Suppose we have a docker-compose.yml file with two services, web and db. We can use the docker-compose logs command to view the logs for both services like this:

$ docker-compose logs

To view the logs for a specific service, we can specify the service name as an argument:

$ docker-compose logs db

We can also use the --followoption to follow the logs in real-time:

$ docker-compose logs -f

To limit the number of log lines displayed, we can use the --tailoption:

$ docker-compose logs --tail 50

These are some of the basic options for using the docker-compose logscommand.

docker-compose build

https://media1.giphy.com/media/hvaAO07wVOArutF1eB/giphy.gif?cid=7941fdc6xm9g9yfo08uauay441u74xhqotad9ff1co92bziq&ep=v1_gifs_search&rid=giphy.gif&ct=g

The docker-compose buildcommand is used to build the Docker images for the services defined in a docker-compose.ymlfile. It reads the Dockerfilein each service's build context and generates an image based on the instructions defined in the Dockerfile. It also tags the image with the service name and a version if specified.

The docker-compose build command supports several options, some of which are:

  • -force-rm: Removes intermediate containers and forces a new build.
  • -no-cache: Builds the image without using cache.
  • -pull: Always attempts to pull a newer version of the image.

Here is an example usage of docker-compose build command:

version: '3.8'
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile

In this example, the web service is built using the Dockerfilein the current directory (. ). We can then run docker-compose buildto build the image for the web service.

$ docker-compose build
Building web
Step 1/5 : FROM node:14
 ---> 0123456789ab
Step 2/5 : WORKDIR /app
 ---> Using cache
 ---> 9876543210fe
Step 3/5 : COPY package*.json ./
 ---> Using cache
 ---> fedcba987654
Step 4/5 : RUN npm install
 ---> Using cache
 ---> 4567890abcde
Step 5/5 : COPY . .
 ---> 0123456789ab
Successfully built 0123456789ab
Successfully tagged myapp_web:latest

This will build the webservice using the Dockerfilein the current directory, and tag the resulting image with the name myapp_web:latest.

To build a single service in a Docker Compose file, you can use the docker-compose build command followed by the name of the service you want to build. Here is an example:

Suppose you have a docker-compose.yml file that defines two services, app and database. To build only the app service, you can use the following command:

docker-compose build app

This will build the Docker image for the app service based on the instructions in its Dockerfile. The database service will not be built because it was not specified.

If you want to rebuild the image for the app service even if it has already been built, you can add the --no-cache option:

docker-compose build --no-cache app

This will force Docker to rebuild the image from scratch, ignoring any previously cached layers.

Note that if the app service depends on other services, those services will also be built if they have not been built yet. If you only want to build the app service and not its dependencies, you can use the --no-deps option:

docker-compose build --no-deps app

This will skip building any services that the appservice depends on.

docker-compose config

https://media0.giphy.com/media/ck4GQsHFbbbcdMhGQk/giphy.gif?cid=7941fdc6i1umwjir3yck4jnommqcjipnrrn0xt5t6i5k9hz3&ep=v1_gifs_search&rid=giphy.gif&ct=g

The docker-compose config command is used to validate and view the Compose file in its final merged form after variable substitution and interpolation. It can be used to check if there are any syntax errors or configuration issues in the Compose file.

When run, docker-compose config reads the docker-compose.yml file, processes it and prints the resulting configuration to the standard output.

Here's an example usage:

docker-compose config

This will check and display the final configuration for the services defined in the docker-compose.yml file.

You can also specify a specific Compose file by using the -f option, like this:

docker-compose -f docker-compose.prod.yml config

This will check and display the final configuration for the services defined in the docker-compose.prod.yml file.

Note that docker-compose config does not actually start or stop any containers, it simply validates and displays the configuration.

docker-compose exec

https://media2.giphy.com/media/26uf4LsTj87JjVDbO/giphy.gif?cid=7941fdc6g3colx38wzqtg839hxn13jt8tqwahkns3lrs79vo&ep=v1_gifs_search&rid=giphy.gif&ct=g

The docker-compose exec command is used to run a command in a running container. This command allows you to interact with a container as if you are logged in to it, without having to start a new shell session.

The basic syntax of the command is:

docker-compose exec [options] service_name command

Here, service_name is the name of the service you want to execute the command in, and command is the command you want to execute in the service's container.

Some common options used with docker-compose exec are:

  • u: This option allows you to specify the user context in which the command should be run.
  • T: This option disables pseudo-tty allocation, which is useful when running non-interactive commands.
  • -index: This option allows you to specify which container instance to run the command in. By default, the first instance is used.

For example, let's say you have a service named web that runs a web server, and you want to run a command in its container to check the version of a software package:

docker-compose exec web bash -c "apt show my-package | grep Version"

This will execute the bash -c "apt show my-package | grep Version"command in the web service's container, and print the output to the terminal.

docker-compose pull

https://media0.giphy.com/media/SsIZAm4IDC6yUQMa45/giphy.gif?cid=7941fdc61129wuqb8xlun900btin2e6lgdr3f2wi5kx92tzo&ep=v1_gifs_search&rid=giphy.gif&ct=g

The docker-compose pull command is used to pull (download) images for all services listed in the docker-compose.yml file. This command is used to ensure that the latest image of each service is downloaded before starting the services. If there are any updates available for the images, docker-compose pull will download them.

Here is an example of using docker-compose pull command:

Assume that you have a docker-compose.yml file that specifies two services, web and db, as follows:

version: '3'
services:
  web:
    image: nginx:latest
  db:
    image: mysql:latest

To download the latest images for both services, you can run the following command:

docker-compose pull

This will pull the latest nginxand mysqlimages from Docker Hub. If you have already pulled the images before, docker-compose pullwill only download the updates for the images, if any.

docker-compose push

https://media1.giphy.com/media/IeLIp5J7CeEz3rQjOU/giphy.gif?cid=7941fdc60leidesjrvf6e6twhxh09zuhb0d4smujiz89m5ff&ep=v1_gifs_search&rid=giphy.gif&ct=g

The docker-compose push command is used to push images of the services defined in the docker-compose.ymlfile to a Docker registry. This command assume that you are pushing an image you have built locally.

The basic syntax of the command is as follows:

docker compose push [OPTIONS] [SERVICE...]

where [SERVICE...]is an optional list of services to push. If no service is specified, all services defined in the docker-compose.yml file are pushed.

services:
  service1:
    build: .
    image: localhost:5000/yourimage  ## goes to local registry

  service2:
    build: .
    image: your-dockerid/yourimage  ## goes to your repository on Docker Hub

To push the images of these services to a Docker registry, run the following command:

docker-compose push

This command will push the service2 to the docker Hub registry and service1 to local registry.

docker-compose rm

https://media3.giphy.com/media/l0HFkA6omUyjVYqw8/giphy.gif?cid=7941fdc6rk7uhyvdiz3pubafrftwwivzhdutuf9f31w4swk4&ep=v1_gifs_search&rid=giphy.gif&ct=g

The docker-compose rmcommand is used to remove stopped containers created by the docker-compose upcommand along with their respective volumes. It can be used to clean up any resources that may have been left behind by the containers.

By default, the docker-compose rm command will remove all stopped containers associated with the current docker-compose.yml file. However, it is also possible to target a specific service or container using the --service or --container options.

Here's the basic syntax of the docker-compose rm command:

docker-compose rm [options] [SERVICE...]

Some common options that can be used with the docker-compose rm command are:

  • -stop : Stops the containers before removing them.
  • -force : Forces the removal of the containers even if they are running.
  • -volumes : Removes the anonymous volumes associated with the containers.

For example, to remove all stopped containers and their volumes for the services defined in the docker-compose.yml file, you can run the following command:

docker-compose rm

To remove a specific service and its stopped containers, you can use the --service option followed by the name of the service:

docker-compose rm --service myservice

And to force the removal of running containers, you can use the --forceoption:

docker-compose rm --force

docker-compose run

https://media1.giphy.com/media/30MgfpdDZHMsw/giphy.gif?cid=7941fdc6ziz89xbj4uwo3xz82j6qzn6wwp7cubzl3mmp1i4q&ep=v1_gifs_search&rid=giphy.gif&ct=g

The docker-compose run command is used to run a one-off command on a service defined in a Compose file. This allows you to run a command within a specific environment defined by the Compose file.

The basic syntax of the command is as follows:

docker-compose run [options] [service_name] [command]

Here, [options] are the additional options that you can pass to the command, [service_name] is the name of the service to run the command on, and [command] is the command to run.

Some common options used with the docker-compose run command are:

  • d or -detach: Run the container in the background and print the new container ID.
  • e or -env: Set an environment variable for the container.
  • -name: Assign a name to the container.
  • v or -volume: Mount a volume from the host to the container.

For example, to run the command ls on the web service defined in a Compose file, you would use the following command:

docker-compose run web ls

This would start a container for the webservice and run the lscommand inside it. Once the command finishes, the container will be stopped and removed.

Here are some use cases for the docker-compose runcommand:

  1. Run a one-time command: You can use docker-compose run to run a command in a service container just once, without starting the service itself. For example, you can run a database migration script with the following command:

    
     docker-compose run webapp python manage.py migrate
    

    This will start a new container for the webapp service, run the python manage.py migrate command inside it, and then stop and remove the container.

  2. Run a command with environment variables: You can use docker-compose run to set environment variables for a command that you want to run. For example:

     docker-compose run -e DEBUG=True webapp python app.py
    

    This will start a new container for the webapp service, set the DEBUG environment variable to True, run the python app.py command inside it, and then stop and remove the container.

  3. Debug a service: You can use docker-compose run to start a service container in interactive mode and explore its environment. For example:

    
     docker-compose run --service-ports webapp bash
    

    This will start a new container for the webapp service, start a Bash shell inside it, and expose the container's ports so that you can access them from your local machine. This is useful for debugging and troubleshooting.

  4. Test a service: You can use docker-compose run to test a service in isolation, without affecting other services in your composition. For example, you can run unit tests for your web application with the following command:

    
     docker-compose run webapp python manage.py test
    

    This will start a new container for the webapp service, run the python manage.py test command inside it, and then stop and remove the container.

What is -service-ports

The --service-ports option is used with the docker-compose run command to publish all exposed ports of the service containers to the host machine. By default, the container's ports are not exposed to the host. This option is useful when you want to run a one-off command in a service container and need to access its exposed ports from the host machine.

For example, let's say you have a web service in your docker-compose.yml file that exposes port 80:

version: '3'
services:
  web:
    build: .
    ports:
      - "80:80"

Now, you want to run a curlcommand in the webservice container to test the website. You can use the docker-compose runcommand with the --service-portsoption to access the website from the host machine:

docker-compose run --service-ports web curl http://localhost

The --service-portsoption publishes the webservice container's exposed port 80 to the host machine, so you can access the website using http://localhost.

If you found this article helpful, please give it a thumbs up and save it for future reference. If you have any questions or comments, feel free to leave them below.Thank you for reading! I'll see you in the next article.