Docker

Gilson Filho

Alert!

Slides with this 

show updates about Docker and your ecosystem

What is

Docker Begins

What is Docker ?

Docker is an open platform for building, shipping and running distributed applications.

docker.io

What is Docker ?

An open framework to assemble specialized container systems
without reinventing the wheel.

Moby

Going forward, Docker will be assembled using Moby, see Moby and Docker for more details.

Moby

What is Docker Moby ?

Back to THE 90's

MY APP

+

A REAL Server

=

VIRTUAL MACHINEs

VIRTUAL MACHINEs

VIRTUAL MACHINEs

Docker containers

Docker containers

Docker containers

VM

Docker

LXC =

OS-level virtualization for running multiple isolated Linux systems

"LINUX CONTAINERS"

cgroups =

Linux kernel feature that limits and isolates the resource usage

(CPU, disk I/O, network, etc.)

"CONTROL GROUPS"

AUFs =

Filesystem which is based on images where every modification is a diff from the previous one (Like commits in git)

"Adv. multi layered Unification FS"

Docker > 1.11

Engine is now built on runC and containerd

How to Install

HOW TO INSTALL ?

http://docs.docker.com/installation

HOW TO INSTALL ?

http://docs.docker.com/installation

Linux

Debian

Fedora

Ubuntu

Windows e OS X

Windows

OS X

Docker HUB

Over 1.2B Pulls

from Docker Hub

5.6M

65

240K

Pulls per Day

Pulls per Second

Repositories on Docker Hub

Docker Store

next generation of Docker Hub

Docker Store

next generation of Docker Hub

Dictionary

Image

An image is a lightweight, stand-alone, executable package that includes everything needed to run a piece of software, including the code, a runtime, libraries, environment variables, and config files.

Container

A container is a runtime instance of an image – what the image becomes in memory when actually executed. It runs completely isolated from the host environment by default, only accessing host files and ports if configured to do so.

Docker

Commands

Docker Search

~ $ docker search -h
Usage: docker search [OPTIONS] TERM

Search the Docker Hub for images

  --automated=false    Only show automated builds
  --no-trunc=false     Don't truncate output
  -s, --stars=0        Only displays with at least x stars

Docker Search

~ $ docker search hello-world
NAME                                    DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
hello-world                             Hello World! (an example of minimal Docker...   24        [OK]       
tutum/hello-world                       Image to test docker deployments. Has Apac...   12                   [OK]
marcells/aspnet-hello-world             ASP.NET vNext - Hello World                     1                    [OK]
vegasbrianc/docker-hello-world                                                          1                    [OK]
diegomarangoni/devops-hello-world-app   Example application for deploying using Co...   1                    [OK]
nirmata/hello-world                                                                     0                    [OK]
crccheck/hello-world                    Hello World web server in under 2.5 MB          0                    [OK]
poojathote/hello-world                  this is 3rd POC                                 0                    [OK]
adamkdean/hello-world                                                                   0                    [OK]
davelesser/hello-world                                                                  0                    [OK]
milkyway/java-hello-world               Java Hello World Test Docker Image              0                    [OK]
rcarun/hello-world                                                                      0                    [OK]
suryasumukh/hello-world                 A docker auto build test application            0                    [OK]
sixeyed/coreclr-hello-world             A simple Hello World sample, running as a ...   0                    [OK]
keithchambers/docker-hello-world                                                        0                    [OK]
fermayo/hello-world                                                                     0                    [OK]
craigbarrau/docker-java-hello-world     This is an automated build of docker java-...   0                    [OK]
svlapin/docker-hello-world              Hello world automated build                     0                    [OK]
jaimalchohan/hello-world-node-docker    A simple hello world app                        0                    [OK]

Docker pull

~ $ docker pull -h
Usage: docker pull [OPTIONS] NAME[:TAG] | [REGISTRY_HOST[:REGISTRY_PORT]/]NAME[:TAG]

Pull an image or a repository from the registry

  -a, --all-tags=false          Download all tagged images in the repository
  --disable-content-trust=true  Skip image verification

Docker pull

~ $ docker pull hello-world
latest: Pulling from hello-world

535020c3e8ad: Pull complete 
af340544ed62: Pull complete 
Digest: sha256:a68868bfe696c00866942e8f5ca39e3e31b79c1e50feaee4ce5e28df2f051d5c
Status: Downloaded newer image for hello-world:latest
~ $ 

RUN Command

~ $ docker run -h
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

  -a, --attach=[]               Attach to STDIN, STDOUT or STDERR
  --add-host=[]                 Add a custom host-to-IP mapping (host:ip)
  --blkio-weight=0              Block IO weight (relative weight)
  -c, --cpu-shares=0            CPU shares (relative weight)
  [...]

RUN Command

~ $ docker run ubuntu:latest echo "Docker is awesome"    

Unable to find images 'ubuntu:latest' locally
latest: Pulling from ubuntu

d3a1f33e8a5a: Pull complete 
c22013c84729: Pull complete 
d74508fb6632: Pull complete 
91e54dfb1179: Pull complete 
ubuntu:latest: The image you are pulling has been verified.

Digest: sha256:73fbe2308f5f5cb6e343425831b8ab44f10bbd77070ecdfbe4081daa4dbe3ed1
Status: Downloaded newer image for ubuntu:latest

Docker is awesome
~ $ 
~ $ docker run -it ubuntu:latest /bin/bash

root@b91b6d0cf193:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@b91b6d0cf193:/# exit
exit

~ $

RUN Command

~ $ docker run ubuntu:latest echo "Docker is awesome"    

Unable to find images 'ubuntu:latest' locally
latest: Pulling from ubuntu

d3a1f33e8a5a: Pull complete 
c22013c84729: Pull complete 
d74508fb6632: Pull complete 
91e54dfb1179: Pull complete 
ubuntu:latest: The image you are pulling has been verified.

Digest: sha256:73fbe2308f5f5cb6e343425831b8ab44f10bbd77070ecdfbe4081daa4dbe3ed1
Status: Downloaded newer image for ubuntu:latest

Docker is awesome
~ $ 

images & rmi command

~ $ docker images -h
Usage: docker images [OPTIONS] [REPOSITORY]

List images

  -a, --all=false      Show all images (default hides intermediate images)
  --digests=false      Show digests
  -f, --filter=[]      Filter output based on conditions provided
  --help=false         Print usage
  --no-trunc=false     Don't truncate output
  -q, --quiet=false    Only show numeric IDs

images & rmi command

~ $ docker images
REPOSITORY                             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                                 latest              91e54dfb1179        16 minutes ago      188.4 MB
hello-world                            latest              af340544ed62        4 minutes ago       960 B

images & rmi command

~ $ docker images
REPOSITORY                             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                                 latest              91e54dfb1179        16 minutes ago      188.4 MB
hello-world                            latest              af340544ed62        4 minutes ago       960 B
~ $ docker rmi -f hello-world                         
Untagged: hello-world:latest
Deleted: af340544ed62de0680f441c71fa1a80cb084678fed42bae393e543faea3a572c
Deleted: 535020c3e8add9d6bb06e5ac15a261e73d9b213d62fb2c14d752b8e189b2b912
~ $ docker images
REPOSITORY                             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                                 latest              91e54dfb1179        16 minutes ago      188.4 MB

PS & RM command

~ $ docker ps -h
Usage: docker ps [OPTIONS]

List containers

  -a, --all=false       Show all containers (default shows just running)
  --before=""           Show only container created before Id or Name
  -f, --filter=[]       Filter output based on conditions provided
  -l, --latest=false    Show the latest created container, include non-running
  -n=-1                 Show n last created containers, include non-running
  --no-trunc=false      Don't truncate output
  -q, --quiet=false     Only display numeric IDs
  -s, --size=false      Display total file sizes
  --since=""            Show created since Id or Name, include non-running
  --format=[]       Pretty-print containers using a Go template

PS & RM command

~ $ docker ps
CONTAINER ID    IMAGE               COMMAND                CREATED              STATUS             PORTS      NAMES
89951e446cf0    postgres:latest     "/docker-entrypoint.   8 seconds ago        Up 7 seconds       5432/tcp   pensive        
dd5fe50ab712    ubuntu:latest       "sleep 20000000"       41 seconds ago       Up 40 seconds                 adoring      
eea75a0a071f    ubuntu:latest       "/bin/bash"            About a minute ago   Up About a minute             insane      
~ $ 

PS & RM command

~ $ docker rm -f 89951e446cf0
89951e446cf0
~ $ docker ps
CONTAINER ID    IMAGE               COMMAND                CREATED              STATUS             PORTS      NAMES
dd5fe50ab712    ubuntu:latest       "sleep 20000000"       41 seconds ago       Up 40 seconds                 adoring      
eea75a0a071f    ubuntu:latest       "/bin/bash"            About a minute ago   Up About a minute             insane      
~ $ 
~ $ docker ps
CONTAINER ID    IMAGE               COMMAND                CREATED              STATUS             PORTS      NAMES
89951e446cf0    postgres:latest     "/docker-entrypoint.   8 seconds ago        Up 7 seconds       5432/tcp   pensive        
dd5fe50ab712    ubuntu:latest       "sleep 20000000"       41 seconds ago       Up 40 seconds                 adoring      
eea75a0a071f    ubuntu:latest       "/bin/bash"            About a minute ago   Up About a minute             insane      
~ $ 

exec command

~ $ docker exec -h
Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

  -d, --detach=false         Detached mode: run command in the background
  -i, --interactive=false    Keep STDIN open even if not attached
  -t, --tty=false            Allocate a pseudo-TTY
  -u, --user=                Username or UID (format: <name|uid>[:<group|gid>])

exec command

~ $ docker ps
CONTAINER ID    IMAGE               COMMAND                CREATED              STATUS             PORTS      NAMES
89951e446cf0    postgres:latest     "/docker-entrypoint.   8 seconds ago        Up 7 seconds       5432/tcp   pensive       
dd5fe50ab712    ubuntu:latest       "sleep 20000000"       41 seconds ago       Up 40 seconds                 adoring      
eea75a0a071f    ubuntu:latest       "/bin/bash"            About a minute ago   Up About a minute             insane      
~ $ 

exec command

~ $ docker ps
CONTAINER ID    IMAGE               COMMAND                CREATED              STATUS             PORTS      NAMES
89951e446cf0    postgres:latest     "/docker-entrypoint.   8 seconds ago        Up 7 seconds       5432/tcp   pensive       
dd5fe50ab712    ubuntu:latest       "sleep 20000000"       41 seconds ago       Up 40 seconds                 adoring      
eea75a0a071f    ubuntu:latest       "/bin/bash"            About a minute ago   Up About a minute             insane      
~ $ 
~ $ docker exec -it dd5fe50ab712 /bin/bash
root@dd5fe50ab712:/# ls     
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@dd5fe50ab712:/# exit
exit
~ $ 

Docker Volume

data volume is a specially-designated directory within one or more containers that bypasses the Union File System.

Docker Volume

~ $ ls /Users/baptou/myDirectory
file1 file2 file3
~ $ docker run -it -v /Users/baptou/myDirectory:/opt ubuntu:latest /bin/bash
root@29088b02f260:/# ls /opt
file1  file2 file3
root@29088b02f260:/# rm /opt/file2
root@29088b02f260:/# ls /opt
file1 file3
root@29088b02f260:/# exit
exit
~ $ ls /Users/baptou/myDirectory  
file1 file3
~ $ 

Docker COMMIT

~ $ docker commit -h
Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

  -a, --author=""     Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
  -c, --change=[]     Apply specified Dockerfile instructions while committing the image
  -m, --message=""    Commit message
  -p, --pause=true    Pause container during commit

Docker COMMIT

~ $ docker run -d ubuntu /bin/bash -c "apt-get install -y hello"
009e8061df58b8b123ee
~ $ docker commit -m "My first container with a Commit" 009e8061df58b8b123ee gilson/hello
b88f9422f14dc055427d39bf6971f8415511fdaa3182a37869c14c4893664c43
~ $ docker images
REPOSITORY                             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
gilson/hello                        latest              b88f9422f14d        7 seconds ago       189.3 MB
feedbackfront                          latest              34cd8b4a3d8b        4 weeks ago         163 MB
offer/feedbackfront                    latest              63a5a64ddc7a        4 weeks ago         163 MB
offer/feedback-front                   latest              63a5a64ddc7a        4 weeks ago         163 MB

~ $ docker run gilson/hello         
Reading package lists...
Building dependency tree...
Reading state information...
hello is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

~ $ docker run -it gilson/hello /bin/bash
root@df8d31633a9a:/# hello
Hello, world!
root@df8d31633a9a:/# exit
exit
~ $ 

Docker push

~ $ docker push -h
Usage: docker push NAME[:TAG]

Push an image or a repository to the registry

--disable-content-trust=true   Skip image signing

Docker push

~ $ docker push baptwaels/hello
The push refers to a repository [baptwaels/hello] (len: 1)
b88f9422f14d: Image push failed 

Please login prior to push:
Username: baptwaels
Password: 
Email: bwaels@gmail.com
WARNING: login credentials saved in /Users/baptou/.dockercfg.
Login Succeeded
The push refers to a repository [baptwaels/hello] (len: 1)
b88f9422f14d: Image already exists 
91e54dfb1179: Image successfully pushed 
d74508fb6632: Image successfully pushed 
c22013c84729: Image successfully pushed 
d3a1f33e8a5a: Image successfully pushed 
Digest: sha256:d659f9011eab6d04b3d9fd9f6324e23505bd1299c52d295c4b04ebe3e58878ce

~ $ 

Docker push

FROM ubuntu:latest

RUN apt-get install vim -y

Docker build

Dockerfile

~ $ docker build -t myubuntu .
~ $ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
myubuntu            latest              4b205af179df        5 seconds ago       188.9 MB

Shell

Docker system

Usage:  docker system COMMAND

Manage Docker

Options:
      --help   Print usage

Commands:
  df          Show docker disk usage
  events      Get real time events from the server
  info        Display system-wide information
  prune       Remove unused data

Run 'docker system COMMAND --help' for more information on a command.

Docker system

~ $ docker system df

TYPE                TOTAL               ACTIVE              SIZE                RECLAIMABLE
Images              8                   5                   1.296GB             729.3MB (56%)
Containers          6                   1                   408B                345B (84%)
Local Volumes       4                   4                   168.6MB             0B (0%)

system df

Docker system

~ $ docker system df -v
Images space usage:

REPOSITORY                   TAG                 IMAGE ID            CREATED ago      (...)
pen_banco                    latest              8e40d6a09c39        About an hour ago
postgres                     9.3                 0dd7d39ff91b        2 days ago
postgres                     latest              ca3a55649cfc        2 days ago
docker_apoiador-banco        latest              556796db6132        4 days ago
mdillon/postgis              9.5                 95ef56d0b84b        6 days ago
rabbitmq                     3-management        281ee777b811        12 days ago
hello-world                  latest              48b5124b2768        4 months ago
jhipster/jhipster-registry   v2.5.4              f5ac510b0620        6 months ago

Containers space usage:

CONTAINER ID        IMAGE                               COMMAND                  LOCAL VOLUMES  (...)
b484a4673c73        postgres:latest                     "docker-entrypoint..."   0
00515c9b728a        docker_banco-teste                  "docker-entrypoint..."   1
25e7b744d869        docker_apoiador-banco               "docker-entrypoint..."   1
8bb66b298716        rabbitmq:3-management               "docker-entrypoint..."   1
6718c15a2bde        jhipster/jhipster-registry:v2.5.4   "java -Djava.secur..."   1
ff1de954a916        hello-world                         "/hello"                 0

Local Volumes space usage:

VOLUME NAME                                                        LINKS               SIZE
31f5e396aefc175501357305306bbb691243f9f41a98bb1aeca36d129d36c97f   1                   2.597MB
dc091727d965df0debed796e5381c47001ab8881141fde44fa578bb2a169850b   1                   151.7kB
e60cb462042b9b52800f019b13af1e7d49856d3f57ea7515d02eba5741960254   1                   82.96MB
09212ad7c68f115564f0e5f06248df66458cf5618f814d17af67a400bc7aba52   1                   82.93MB

system df -v

Docker system

~ $ docker system prune

WARNING! This will remove:
        - all stopped containers
        - all volumes not used by at least one container
        - all networks not used by at least one container
        - all dangling images
Are you sure you want to continue? [y/N]

system prune

Dockerfile

 A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.

FROM ubuntu:latest

# (...)

Dockerfile

Command FROM

Sets the Base Image for subsequent instructions. As such, a valid Dockerfile must have FROM as its first instruction. The image can be any valid image – it is especially easy to start by pulling an image from the Public Repositories.

FROM ubuntu:latest
MAINTAINER Gilson Filho <me@gilsondev.in>

# (...)

Dockerfile

Command MAINTAINER

The MAINTAINER instruction allows you to set the Author field of the generated images.

FROM ubuntu:latest

# MAINTAINER ...

RUN apt-get update

# Other dependencies...

RUN apt-get install -y mysql-server

# Configure database and user...

RUN ["mysql", "-u", "root", "-p"]

Dockerfile

Command RUN

The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting comitted image will be used for the next step in the Dockerfile.

FROM ubuntu:latest

# MAINTAINER ...

RUN apt-get update

# Other dependencies...

RUN apt-get install -y mysql-server

# Configure database and user...

CMD ["mysqld"]

Dockerfile

Command CMD

The main purpose of a CMD is to provide defaults for an executing container. There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect.

FROM ubuntu:latest

# MAINTAINER ...

RUN apt-get update

# Other dependencies...

RUN apt-get install -y mysql-server

# Configure database and user...

EXPOSE 3306

CMD ["mysqld"]

Dockerfile

Command EXPOSE

The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime. EXPOSE does not make the ports of the container accessible to the host.

FROM ubuntu:latest

# MAINTAINER ...

ENV MYSQL_MAJOR 5.7

RUN apt-get update

# Other dependencies...

RUN apt-get install -y mysql-server

# (...)

Dockerfile

Command ENV

The ENV instruction sets the environment variable <key> to the value <value>. This value will be in the environment of all “descendant” Dockerfile commands and can be replaced inline in many as well.

FROM ubuntu:latest

# MAINTAINER ...

ENV MYSQL_MAJOR 5.7

RUN apt-get update

# Other dependencies...

RUN apt-get install -y mysql-server

# Configure database and user...

ADD custom.conf /var/lib/mysql

# (...)

Dockerfile

Command ADD

The ADD instruction copies new files, directories or remote file URLs from <src> and adds them to the filesystem of the container at the path <dest>.

FROM ubuntu:latest

# MAINTAINER ...

ENV MYSQL_MAJOR 5.7

RUN apt-get update

# Other dependencies...

RUN apt-get install -y mysql-server

# Configure database and user...

COPY custom.conf /var/lib/mysql

# (...)

Dockerfile

Command COPY

The COPY instruction copies new files or directories from <src> and adds them to the filesystem of the container at the path <dest>.

FROM ubuntu:latest

# MAINTAINER ...

RUN apt-get update

RUN apt-get install -y python-pip

RUN pip install ipython

ENTRYPOINT ["ipython"]

Dockerfile

Command ENTRYPOINT

An ENTRYPOINT allows you to configure a container that will run as an executable.

CMD or ENTRYPOINT?

  1. Dockerfile should specify at least one of CMD or ENTRYPOINT commands.

  2. ENTRYPOINT should be defined when using the container as an executable.

  3. CMD should be used as a way of defining default arguments for an ENTRYPOINT command or for executing an ad-hoc command in a container.

  4. CMD will be overridden when running the container with alternative arguments.

FROM ubuntu:latest

# (...)

RUN mkdir /myvol
RUN echo "hello world" > /myvol/greeting
VOLUME /myvol

Dockerfile

Command VOLUME

The VOLUME instruction creates a mount point with the specified name and marks it as holding externally mounted volumes from native host or other containers.

The docker run command initializes the newly created volume with any data that exists at the specified location within the base image.

FROM ubuntu:latest

RUN mkdir -p /var/whoami
RUN chmod -R 777 /var/whoami

RUN whoami >> /var/whoami/root.txt

# Criando usuario
RUN useradd basis -p 1234

USER basis

RUN whoami >> /var/whoami/basis.txt

Dockerfile

Command USER

The USER instruction sets the user name or UID to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile.

FROM ubuntu:latest

RUN pwd

WORKDIR /opt

RUN pwd
RUN touch file_opt.txt

WORKDIR /var

RUN pwd
RUN touch file_var.txt

Dockerfile

Command WORKDIR

The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction.

FROM ubuntu:latest

# Other configurations...

ONBUILD RUN echo "Echo message made by image base"

Dockerfile

Command ONBUILD

The ONBUILD instruction adds to the image a trigger instruction to be executed at a later time, when the image is used as the base for another build. The trigger will be executed in the context of the downstream build, as if it had been inserted immediately after the FROM instruction in the downstream Dockerfile.

FROM ubuntu:latest

# Other configurations...

HEALTHCHECK --interval=5m --timeout=3s \
  CMD curl -f http://localhost/ || exit 1

Dockerfile

Command HEALTHCHECK

The HEALTHCHECK instruction tells Docker how to test a container to check that it is still working. This can detect cases such as a web server that is stuck in an infinite loop and unable to handle new connections, even though the server process is still running.

Other commands

Orquestration

App

Database

link

App

link

Storage

link

Storage

link

link

App

Database

link

App

link

Storage

link

Storage

link

link

Docker Host

Docker Host

Docker Host

Docker Host

Docker Host

Orquestration

Orchestration is a broad term that refers to the container scheduling, cluster management, and possibly the provision of additional hosts.

Tools

  • Docker Swarm
  • Fleet
  • Kubernetes
  • Mesos

Docker Compose

 Compose is a tool for defining and running multi-container Docker applications.

Docker Compose

  1. Define your app’s environment with a Dockerfile so it can be reproduced anywhere.

  2. Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.

  3. Lastly, run docker-compose up and Compose will start and run your entire app.

version: '2'
services:
  db:
    image: mysql:5.7
    volumes:
      - "./.data/db:/var/lib/mysql"
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: wordpress
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress

  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    links:
      - db
    ports:
      - "8000:80"
    restart: always
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_PASSWORD: wordpress

docker-compose.yml

web:
  build: .
  ports:
    - "5000:5000"
  volumes:
    - .:/code
redis:
  image: redis

Versions

Compose files using the version 2 syntax must indicate the version number at the root of the document. Compose files that do not declare a version are considered “version 1”.

docker-compose.yml

version: '2'
services:
  web:
    build: .
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  redis:
    image: redis

Version 1

Version 2

web:
  build: .

# (...)

Command BUILD

Configuration options that are applied at build time. Can be specified either as a string containing a path to the build context, or an object with the path specified under context and optionally dockerfile and args.

docker-compose.yml

version: '2'
services:
  web:
    build:
      context: ./app
      dockerfile: Dockerfile-alternate

# (...)
version: '2'
services:
  web:
    # hub.docker.com/_/ubuntu:latest
    image: ubuntu:latest

# (...)

Command IMAGE

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

docker-compose.yml

version: '2'
services:
  web:
    image: example-registry.com:4000/postgresql

# (...)

Command VOLUME

Mount paths or named volumes, optionally specifying a path on the host machine (HOST:CONTAINER), or an access mode (HOST:CONTAINER:ro).

docker-compose.yml

# (...)
  web:
    image: mysql:5.1
    volumes:
      # Just specify a path and let the Engine create a volume
      - /var/lib/mysql
    
      # Specify an absolute path mapping
      - /opt/data:/var/lib/mysql
    
      # Path on the host, relative to the Compose file
      - ./cache:/tmp/cache
    
      # User-relative path
      - ~/configs:/etc/configs/:ro
    
      # Named volume
      - datavolume:/var/lib/mysql

Command VOLUME_FROM

Mount paths or named volumes, optionally specifying a path on the host machine (HOST:CONTAINER), or an access mode (HOST:CONTAINER:ro).

docker-compose.yml

# (...)
  web:
    image: mysql:5.1
    volumes:
      - /var/lib/mysql
    volumes_from:
     - service_name
     - service_name:ro
     - container:container_name
     - container:container_name:rw

Command ENVIRONMENT

Add environment variables.  You can use either an array or a dictionary.

docker-compose.yml

version: '2'
services:
  db:
    image: mysql:5.7
    volumes:
      - "./.data/db:/var/lib/mysql"
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: wordpress
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress
version: '2'
services:
  db:
    image: mysql:5.7
    volumes:
      - "./.data/db:/var/lib/mysql"
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=wordpress
      - MYSQL_DATABASE=wordpress
      - MYSQL_USER=wordpress
      - MYSQL_PASSWORD=wordpress

Command LINKS

Link to containers in another service. Either specify both the service name and a link alias (SERVICE:ALIAS), or just the service name.

docker-compose.yml

version: '2'
services:
  db:
    image: mysql:5.7
    volumes:
      - "./.data/db:/var/lib/mysql"
    environment:
      - MYSQL_ROOT_PASSWORD=wordpress
      - MYSQL_DATABASE=wordpress
      - MYSQL_USER=wordpress
      - MYSQL_PASSWORD=wordpress
redis:
    # (...)
web:
  image: wordpress:latest
  links:
   - db
   - redis

Command DEPENDS_ON

Express dependency between services, which has two effects:

  • docker-compose up will start services in dependency order. In the following example, db and redis will be started before web.

  • docker-compose up SERVICE will automatically include SERVICE’s dependencies. In the following example, docker-compose up web will also create and start db and redis.

docker-compose.yml

version: '2'
services:
  db:
    image: mysql:5.7
    # (...)
web:
  image: wordpress:latest
  depends_on:
    - redis
    - db

Command PORTS

Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).

docker-compose.yml

version: '2'
services:
  wordpress:
    image: wordpress:latest
    ports:
      - "8000:80"
version: '2'
services:
  wordpress:
    image: wordpress:latest
    ports:
     - "3000"
     - "3000-3005"
     - "8000:8000"
     - "9090-9091:8080-8081"
     - "49100:22"
     - "127.0.0.1:8001:8001"
     - "127.0.0.1:5000-5010:5000-5010"

Command COMMAND

Override the default command.

docker-compose.yml

version: '2'
services:
  wordpress:
    image: wordpress:latest
    # Override 'CMD ["apache2-foreground"]' of wordpress Dockerfile
    command: bash
    ports:
      - "8000:80"

Command ENTRYPOINT

Override the default entrypoint.

docker-compose.yml

version: '2'
services:
  wordpress:
    image: wordpress:latest
    # Override 'CMD ["./entrypoint.sh"]' of wordpress Dockerfile
    entrypoint: ./custom-entrypoint.sh
    ports:
      - "8000:80"

Command ENV_FILE

Add environment variables from a file. Can be a single value or a list.

docker-compose.yml

version: '2'
services:
  wordpress:
    image: wordpress:latest
    ports:
      - "8000:80"
  env_file: .env
version: '2'
services:
  wordpress:
    image: wordpress:latest
    ports:
      - "8000:80"
    env_file:
      - ./common.env
      - ./apps/web.env
      - /opt/secrets.env

Command EXPOSE

Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.

docker-compose.yml

version: '2'
services:
  db:
    image: mysql:5.7
    volumes:
      - "./.data/db:/var/lib/mysql"
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: wordpress
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress
    expose:
      - "3306"

Command EXTENDS

Extend another service, in the current file or another, optionally overriding configuration.

docker-compose.yml

web:
  extends:
    file: common-services.yml
    service: webapp
webapp:
  build: .
  ports:
    - "8000:8000"
  volumes:
    - "/data"

common-services.yml

docker-compose.yml

Resources

(dica do Eustáquio ♥️)

Examples

Getting Started

Email: me@gilsondev.in

Blog: gilsondev.in

Telegram/Github: @gilsondev

Twitter: @gilsonfilho

Questions?

Made with Slides.com