Basic example
yaml
1# docker-compose.yml2version: '3.8'34services:5web:6build:7# build from Dockerfile8context: ./dir9dockerfile: Dockerfile10ports:11- '8080:80'12volumes:13- .:/code14db:15image: mysql
Commands
docker compose - link
shellscript
1Usage: docker compose [OPTIONS] COMMAND23Define and run multi-container applications with Docker.45Options:6--ansi string Control when to print ANSI control characters ("never"|"always"|"auto") (default "auto")7--compatibility Run compose in backward compatibility mode8--env-file stringArray Specify an alternate environment file.9-f, --file stringArray Compose configuration files10--parallel int Control max parallelism, -1 for unlimited (default -1)11--profile stringArray Specify a profile to enable12--project-directory string Specify an alternate working directory13(default: the path of the, first specified, Compose file)14-p, --project-name string Project name1516Commands:17build Build or rebuild services18config Parse, resolve and render compose file in canonical format19cp Copy files/folders between a service container and the local filesystem20create Creates containers for a service.21down Stop and remove containers, networks22events Receive real time events from containers.23exec Execute a command in a running container.24images List images used by the created containers25kill Force stop service containers.26logs View output from containers27ls List running compose projects28pause Pause services29port Print the public port for a port binding.30ps List containers31pull Pull service images32push Push service images33restart Restart service containers34rm Removes stopped service containers35run Run a one-off command on a service.36start Start services37stop Stop services38top Display the running processes39unpause Unpause services40up Create and start containers41version Show the Docker Compose version information
docker compose up - link
shellscript
1Usage: docker compose up [OPTIONS] COMMAND23Builds, (re)creates, starts, and attaches to containers for a service.45Options:6--abort-on-container-exit Stops all containers if any container was stopped. Incompatible with -d7--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 background12--exit-code-from Return the exit code of the selected service container. Implies --abort-on-container-exit13--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)
docker compose down - link
shellscript
1Usage: docker compose down [OPTIONS] COMMAND23Stops containers and remove containers, networks, volumes, and images created by up.45Options: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
1version: '3.8'2services:3webapp:4build: ./dir
Or, as an object with path specified under context and optionally Dockerfile and args:
yaml
1version: '3.8'2services:3webapp:4build:5context: ./dir6dockerfile: Dockerfile-alternate7args:8buildno: 1
Specify the image to start the container from. Can either be a repository/tag or a partial image ID.
yaml
1version: '3.8'2services:3webapp:4image: 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
1ports: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
1ports:2- target: 803published: 80804protocol: tcp5mode: host
command
Override the default command. And the command can also be a list, in a manner similar to Dockerfile.
yaml
1# command to execute2command: bundle exec thin -p 30003command: ["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 entrypoint2entrypoint: /app/start.sh3entrypoint: ["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
1environment:2RACK_ENV: development3SHOW: 'true'
yaml
1environment:2- RACK_ENV=development
depends_on
Express dependency between services. Service dependencies cause the following behaviors:
docker-compose upstarts services in dependency order. In the following example,dbandredisare started beforeweb.docker-compose up SERVICEautomatically includesSERVICE's dependencies. In the example below,docker-compose up webalso creates and startsdbandredis.docker-compose stopstops services in dependency order. In the following example,webis stopped beforedbandredis.- Simple example:
yaml
1version: '3.8'2services:3web:4build: .5depends_on:6- db7- redis8redis:9image: redis10db:11image: 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
1version: '3.8'2services:3web:4image: nginx:alpine5volumes:6- type: volume7source: mydata8target: /data9volume:10nocopy: true11- type: bind12source: ./static13target: /opt/app/static1415db:16image: postgres:latest17volumes:18- '/var/run/postgres/postgres.sock:/var/run/postgres/postgres.sock'19- 'dbdata:/var/lib/postgresql/data'2021volumes:22mydata:23dbdata:
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
1volumes:2# Just specify a path and let the Engine create a volume3- /var/lib/mysql45# Specify an absolute path mapping6- /opt/data:/var/lib/mysql78# Path on the host, relative to the Compose file9- ./cache:/tmp/cache1011# User-relative path12- ~/configs:/etc/configs/:ro1314# Named volume15- 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 typevolume,bind,tmpfsornpipesource: 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 mountedread_only: flag to set the volume as read-onlybind: configure additional bind optionspropagation: the propagation mode used for the bind
volume: configure additional volume optionsnocopy: flag to disable copying of data from a container when a volume is created
tmpfs: configure additional tmpfs optionssize: the size for the tmpfs mount in bytes
yaml
1version: '3.8'2services:3web:4image: nginx:alpine5ports:6- '80:80'7volumes:8- type: volume9source: mydata10target: /data11volume:12nocopy: true13- type: bind14source: ./static15target: /opt/app/static1617networks:18webnet:1920volumes:21mydata:
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
1services:2web:3labels:4com.example.description: 'Accounting webapp'
dns
Custom DNS servers. Can be a single value or a list.
yaml
1services:2web:3dns:4- 8.8.8.85- 8.8.4.4
external_links
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
1services:2web:3external_links:4- redis_15- 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 succeed2healthcheck:3test: ['CMD', 'curl', '-f', 'http://localhost']4interval: 1m30s5timeout: 10s6retries: 37start_period: 40s
extra_hosts
Add hostname mappings. Use the same values as the docker client --add-host parameter.
yaml
1services:2web:3extra_hosts:4- 'somehost:192.168.1.100'
networks
Networks to join, referencing entries under the top-level networks key.
yaml
1services:2some-service:3networks:4- some-network5- other-network
About Myself
Please reach out to connect with me via Linkedin.