Docker Compose Cheat Sheet

Post on

Basic example

yaml

1
# docker-compose.yml
2
version: '3.8'
3
4
services:
5
web:
6
build:
7
# build from Dockerfile
8
context: ./dir
9
dockerfile: Dockerfile
10
ports:
11
- '8080:80'
12
volumes:
13
- .:/code
14
db:
15
image: mysql

Commands

shellscript

1
Usage: docker compose [OPTIONS] COMMAND
2
3
Define and run multi-container applications with Docker.
4
5
Options:
6
--ansi string Control when to print ANSI control characters ("never"|"always"|"auto") (default "auto")
7
--compatibility Run compose in backward compatibility mode
8
--env-file stringArray Specify an alternate environment file.
9
-f, --file stringArray Compose configuration files
10
--parallel int Control max parallelism, -1 for unlimited (default -1)
11
--profile stringArray Specify a profile to enable
12
--project-directory string Specify an alternate working directory
13
(default: the path of the, first specified, Compose file)
14
-p, --project-name string Project name
15
16
Commands:
17
build Build or rebuild services
18
config Parse, resolve and render compose file in canonical format
19
cp Copy files/folders between a service container and the local filesystem
20
create Creates containers for a service.
21
down Stop and remove containers, networks
22
events Receive real time events from containers.
23
exec Execute a command in a running container.
24
images List images used by the created containers
25
kill Force stop service containers.
26
logs View output from containers
27
ls List running compose projects
28
pause Pause services
29
port Print the public port for a port binding.
30
ps List containers
31
pull Pull service images
32
push Push service images
33
restart Restart service containers
34
rm Removes stopped service containers
35
run Run a one-off command on a service.
36
start Start services
37
stop Stop services
38
top Display the running processes
39
unpause Unpause services
40
up Create and start containers
41
version Show the Docker Compose version information

shellscript

1
Usage: docker compose up [OPTIONS] COMMAND
2
3
Builds, (re)creates, starts, and attaches to containers for a service.
4
5
Options:
6
--abort-on-container-exit Stops all containers if any container was stopped. Incompatible with -d
7
--always-recreate-deps Recreate dependent containers. Incompatible with --no-recreate.
8
--attach Attach to service output.
9
--attach-dependencies Attach to dependent containers.
10
--build Build images before starting containers.
11
-d, --detach Detached mode: Run containers in the background
12
--exit-code-from Return the exit code of the selected service container. Implies --abort-on-container-exit
13
--force-recreate Recreate containers even if their configuration and image haven't changed.
14
--no-attach Don't attach to specified service.
15
--no-build Don't build an image, even if it's missing.
16
--no-color Produce monochrome output.
17
--no-deps Don't start linked services.
18
--no-log-prefix Don't print prefix in logs.
19
--no-recreate If containers already exist, don't recreate them. Incompatible with --force-recreate.
20
--no-start Don't start the services after creating them.
21
--pull Pull image before running ("always"|"missing"|"never")
22
--quiet-pull Pull without printing progress information.
23
--remove-orphans Remove containers for services not defined in the Compose file.
24
-V, --renew-anon-volumes Recreate anonymous volumes instead of retrieving data from the previous containers.
25
--scale Scale SERVICE to NUM instances. Overrides the scale setting in the Compose file if present.
26
-t, --timeout Use this timeout in seconds for container shutdown when attached or when containers are already running. (default 0)
27
--timestamps Show timestamps.
28
--wait Wait for services to be running|healthy. Implies detached mode.
29
--wait-timeout timeout waiting for application to be running|healthy. (default 0)

shellscript

1
Usage: docker compose down [OPTIONS] COMMAND
2
3
Stops containers and remove containers, networks, volumes, and images created by up.
4
5
Options:
6
--remove-orphans Remove containers for services not defined in the Compose file.
7
--rmi Remove images used by services. "local" remove only images that don't have a custom tag ("local"|"all")
8
-t, --timeout Specify a shutdown timeout in seconds (default 0)
9
-v, --volumes Remove named volumes declared in the "volumes" section of the Compose file and anonymous volumes attached to containers.

Reference

Build

build can be specified either as a string containing a path to the build context:

yaml

1
version: '3.8'
2
services:
3
webapp:
4
build: ./dir

Or, as an object with path specified under context and optionally Dockerfile and args:

yaml

1
version: '3.8'
2
services:
3
webapp:
4
build:
5
context: ./dir
6
dockerfile: Dockerfile-alternate
7
args:
8
buildno: 1

Specify the image to start the container from. Can either be a repository/tag or a partial image ID.

yaml

1
version: '3.8'
2
services:
3
webapp:
4
image: ubuntu:22.04

ports

Short syntax

There are three options:

  • Specify both ports (HOST:CONTAINER)
  • Specify just the container port (an ephemeral host port is chosen for the host port).
  • Specify the host IP address to bind to AND both ports (the default is 0.0.0.0, meaning all interfaces): (IPADDR:HOSTPORT:CONTAINERPORT). If HOSTPORT is empty (for example 127.0.0.1::80), an ephemeral port is chosen to bind to on the host.

yaml

1
ports:
2
- '8080:80'
3
- '3000'
4
- '127.0.0.1:8001:8001'

Long syntax

The long form syntax allows the configuration of additional fields that can't be expressed in the short form.

  • target: the port inside the container
  • published: the publicly exposed port
  • protocol: the port protocol (tcp or udp)
  • mode: host for publishing a host port on each node, or ingress for a swarm mode port to be load balanced.

yaml

1
ports:
2
- target: 80
3
published: 8080
4
protocol: tcp
5
mode: host

command

Override the default command. And the command can also be a list, in a manner similar to Dockerfile.

yaml

1
# command to execute
2
command: bundle exec thin -p 3000
3
command: ["bundle", "exec", "thin", "-p", "3000"]

entrypoint

Override the default entrypoint, And the entrypoint can also be a list, in a manner similar to Dockerfile.

yaml

1
# override the entrypoint
2
entrypoint: /app/start.sh
3
entrypoint: ["php", "-d", "vendor/bin/phpunit"]

environment

Add environment variables. You can use either an array or a dictionary. Any boolean values (true, false, yes, no) need to be enclosed in quotes to ensure they are not converted to True or False by the YML parser.

yaml

1
environment:
2
RACK_ENV: development
3
SHOW: 'true'

yaml

1
environment:
2
- RACK_ENV=development

depends_on

Express dependency between services. Service dependencies cause the following behaviors:

  • docker-compose up starts services in dependency order. In the following example, db and redis are started before web.
  • docker-compose up SERVICE automatically includes SERVICE's dependencies. In the example below, docker-compose up web also creates and starts db and redis.
  • docker-compose stop stops services in dependency order. In the following example, web is stopped before db and redis.
  • Simple example:

yaml

1
version: '3.8'
2
services:
3
web:
4
build: .
5
depends_on:
6
- db
7
- redis
8
redis:
9
image: redis
10
db:
11
image: postgres

volumes

Mount host paths or named volumes, specified as sub-options to a service.

You can mount a host path as part of a definition for a single service, and there is no need to define it in the top level volumes key.

But, if you want to reuse a volume across multiple services, then define a named volume in the top-level volumes key. Use named volumes with services, swarms, and stack files.

This example shows a named volume (mydata) being used by the web service, and a bind mount defined for a single service (first path under db service volumes). The db service also uses a named volume called dbdata (second path under db service volumes), but defines it using the old string format for mounting a named volume. Named volumes must be listed under the top-level volumes key, as shown.

yaml

1
version: '3.8'
2
services:
3
web:
4
image: nginx:alpine
5
volumes:
6
- type: volume
7
source: mydata
8
target: /data
9
volume:
10
nocopy: true
11
- type: bind
12
source: ./static
13
target: /opt/app/static
14
15
db:
16
image: postgres:latest
17
volumes:
18
- '/var/run/postgres/postgres.sock:/var/run/postgres/postgres.sock'
19
- 'dbdata:/var/lib/postgresql/data'
20
21
volumes:
22
mydata:
23
dbdata:

Short syntax

The short syntax uses the generic [SOURCE:]TARGET[:MODE] format, where SOURCE can be either a host path or volume name. TARGET is the container path where the volume is mounted. Standard modes are ro for read-only and rw for read-write (default).

You can mount a relative path on the host, which expands relative to the directory of the Compose configuration file being used. Relative paths should always begin with . or ...

yaml

1
volumes:
2
# Just specify a path and let the Engine create a volume
3
- /var/lib/mysql
4
5
# Specify an absolute path mapping
6
- /opt/data:/var/lib/mysql
7
8
# Path on the host, relative to the Compose file
9
- ./cache:/tmp/cache
10
11
# User-relative path
12
- ~/configs:/etc/configs/:ro
13
14
# Named volume
15
- datavolume:/var/lib/mysql

Long syntax

The long form syntax allows the configuration of additional fields that can't be expressed in the short form.

  • type: the mount type volume, bind, tmpfs or npipe
  • source: the source of the mount, a path on the host for a bind mount, or the name of a volume defined in the top-level volumes key. Not applicable for a tmpfs mount.
  • target: the path in the container where the volume is mounted
  • read_only: flag to set the volume as read-only
  • bind: configure additional bind options
    • propagation: the propagation mode used for the bind
  • volume: configure additional volume options
    • nocopy: flag to disable copying of data from a container when a volume is created
  • tmpfs: configure additional tmpfs options
    • size: the size for the tmpfs mount in bytes

yaml

1
version: '3.8'
2
services:
3
web:
4
image: nginx:alpine
5
ports:
6
- '80:80'
7
volumes:
8
- type: volume
9
source: mydata
10
target: /data
11
volume:
12
nocopy: true
13
- type: bind
14
source: ./static
15
target: /opt/app/static
16
17
networks:
18
webnet:
19
20
volumes:
21
mydata:

labels

Add metadata to containers using Docker labels. You can use either an array or a dictionary.

It's recommended that you use reverse-DNS notation to prevent your labels from conflicting with those used by other software.

yaml

1
services:
2
web:
3
labels:
4
com.example.description: 'Accounting webapp'

dns

Custom DNS servers. Can be a single value or a list.

yaml

1
services:
2
web:
3
dns:
4
- 8.8.8.8
5
- 8.8.4.4

Link to containers started outside this docker-compose.yml or even outside of Compose, especially for containers that provide shared or common services. external_links follow semantics similar to the legacy option links when specifying both the container name and the link alias (CONTAINER:ALIAS).

yaml

1
services:
2
web:
3
external_links:
4
- redis_1
5
- project_db_1:mysql

healthcheck

Configure a check that's run to determine whether or not containers for this service are "healthy". See the docs for the HEALTHCHECK Dockerfile instruction for details on how healthchecks work.

yaml

1
# declare service healthy when `test` command succeed
2
healthcheck:
3
test: ['CMD', 'curl', '-f', 'http://localhost']
4
interval: 1m30s
5
timeout: 10s
6
retries: 3
7
start_period: 40s

extra_hosts

Add hostname mappings. Use the same values as the docker client --add-host parameter.

yaml

1
services:
2
web:
3
extra_hosts:
4
- 'somehost:192.168.1.100'

networks

Networks to join, referencing entries under the top-level networks key.

yaml

1
services:
2
some-service:
3
networks:
4
- some-network
5
- other-network

About Myself

Please reach out to connect with me via Linkedin.