Dockerfiel与docker-compose

Dockerfile used to build the mirror, docker-compose.yml used to launch a range of services. Conventions dockerfile command in uppercase.

And listed herein portion Dockerfile docker-compose usage and common commands

 

Dockerfile:

FROM

  For the specified base image, and it must be the first instruction.

  If not in any mirror-based, then the wording is: FROM scratch.

  At the same time means that the next instruction will be written as the start of the first mirror layer

grammar:

  FROM <image>
  FROM <image>:<tag>
  FROM <image>:<digest> 

  Three kinds of writing, where <tag> and <digest> is optional, if not selected, the default value is latest

 

RUN

  Function to run the specified command

RUN command takes two forms

  1. RUN <command>
  2. RUN ["executable", "param1", "param2"]

  The first direct order with shell behind

  The default / bin / sh -c on the linux operating system

  Default cmd / S / C in the windows operating system

  The second is similar to a function call.

  executable can be understood as an executable file, it is behind the two parameters. 

Both versions comparison:

  RUN /bin/bash -c source $HOME/.bashrc; echo $HOME

  RUN ["/bin/bash", "-c", "echo hello"]

  Note: Do not write more multi-line commands RUN, because each instruction will establish Dockerfile in one, how many how many layers RUN to build a mirror, the mirror will cause a bloated, multi-layer, not only increases the time component deployment , but also prone to error.

RUN line breaks when writing is \

 

CMD

  Command function for the container start to run

There are three written grammar

  1. CMD ["executable","param1","param2"]
  2. CMD ["param1","param2"]
  3. CMD command param1 param2

  The third is better understood, it is executed when the shell this way and writing

  The first and second are actually an executable file with the parameters of the form

 

Illustrate two way:

  CMD [ "sh", "-c", "echo $HOME"

  CMD [ "echo", "$HOME" ]

  Additional details: This side must use double quotes including parameter is "not a single quotation mark must not be written in single quotes.

  The reason is that the transmission parameters, docker parsing a JSON array

 

RUN & CMD

  Do not RUN CMD and confused.

  RUN command is run, and member of the container to submit operating results

  CMD is a command to execute when the container starts, does not run in the components, component tightly specified when this command in the end what it is like

 

LABEL

  Function is to specify a label for the mirror

grammar:

  LABEL <key>=<value> <key>=<value> <key>=<value> ...

Can have a plurality of kinds Dockerfile LABEL, as follows:

  LABEL "com.example.vendor"="ACME Incorporated"
  LABEL com.example.label-with-value="foo"
  LABEL version="1.0"
  LABEL description="This text illustrates \
  that label-values can span multiple lines."

But I do not recommend this writing, it is best to write a line, such as the need to change the line is too long, then use \ symbol

as follows:

  LABEL multi.label1="value1" \
  multi.label2="value2" \
  other="value3"

Description: LABEL will inherit the base image species LABEL, such as encountering the same key, the values ​​override

 

MAINTAINER

Specifies the author

grammar:

  MAINTAINER <name>

 

EXPOSE

  Function to monitor the runtime container port exposed to the outside

  But EXPOSE does not make the container port access hosts

  If you want to make the container and the host port mapping relation, must be added -P parameter when the vessel started

 

ENV

  Function to set the environment variable

There are two grammar

  1. ENV <key> <value>
  2. ENV <key>=<value> ...

  The difference is that the first one is the time to set up a second is set more than

 

ADD

   A copy command to copy the file to the mirror

  If the virtual machine container imagine two linux server, then this command is similar to scp, scp just need to add permissions to a user name and password authentication, but without ADD.

The syntax is as follows:

  1. ADD <src>... <dest>
  2. ADD ["<src>",... "<dest>"]

  Fill <dest> path can be absolute in the vessel may be a path relative to the working directory

  <Src> may be a local file or a local archive, it can also be a url

  If <src> written a url, then the ADD command is similar to wget

As in the following versions are possible:

  ADD test relativeDir/ 

  ADD test /relativeDir

  ADD http://example.com/foobar /

  Try not to <scr> written in a folder, if <src> is a folder, and copy the contents of an entire directory, including file system metadata

 

COPY

  Look at this name to know, but also a copy command

The syntax is as follows:

  1. COPY <src>... <dest>
  2. COPY ["<src>",... "<dest>"]

The difference between ADD

  COPY of <src> can be a local file, ADD copy if it is a compressed file, extract it to the target path, consistent with other uses

 

ENTRYPOINT

  Function is the default command at startup

The syntax is as follows:

  1. ENTRYPOINT ["executable", "param1", "param2"]
  2. ENTRYPOINT command param1 param2

  The second is to write shell

  The first is an executable file additional parameters

And CMD comparison shows (maybe too much like a command, but can also be used in conjunction):

1. The same point:

  Only write one, if you write a multiple, then only the last one to take effect

  When the container up and running, running the same opportunity

2. Different points:

   ENTRYPOINT will not be covered by operational command, and will be covered CMD

   If we also wrote ENTRYPOINT and CMD in Dockerfile species, and CMD command is not a complete executable command, CMD will be specified as a parameter ENTRYPOINT of content

as follows:

  FROM ubuntu
  ENTRYPOINT ["top", "-b"]
  CMD ["-c"]

  If we also write Dockerfile planted ENTRYPOINT and CMD, and CMD is a complete command, then they two will cover each other who is who in the final to take effect

as follows:

  FROM ubuntu
  ENTRYPOINT ["top", "-b"]
  CMD ls -al

  It will execute ls -al, top -b will not be executed.

 

VOLUME

  Mounting capabilities can be realized, Mainland folder can be container or other folders hanging on to this container

The syntax is:

  VOLUME ["/data"]

Description:

  [ "/ Data"] may be a JsonArray, may be a plurality of values. So are several versions are correct

  VOLUME ["/var/log/"]

  VOLUME / var / log

  VOLUME / var / log / var / db

  When general usage scenarios that require persistent data storage containers using AUFS, this kind of data the file system can not be sustained, when the container is closed, all changes will be lost.

Therefore, use this command when the data needs to be persisted.

 

USER

  Set user-initiated container may be a user name or UID, so that only the following two written is correct

  USER daemo

  USER UID

  Note: If you set a container to a user daemon to run, then RUN, CMD and ENTRYPOINT would go running to the user

 

WORKDIR

grammar:

  WORKDIR /path/to/workdir

  Set the working directory, the entry into force of the RUN, CMD, ENTRYPOINT, COPY, ADD. If there is created, you can also set multiple times.

Such as:

  WORKDIR /a
  WORKDIR b
  WORKDIR c
  RUN pwd

  Pwd result of execution is / a / b / c

 

  WORKDIR can resolve environment variables

  Such as:

  ENV DIRPATH /path

  WORKDIR $DIRPATH/$DIRNAME
  RUN pwd

  The results pwd is / path / $ DIRNAME

 

ARG

grammar:

  ARG <name>[=<default value>]

  Set variable command, ARG command defines a variable, build create mirrored docker when using --build-arg <varname> = <value> specify the parameters

  If the user specifies a parameter not defined at build mirroring Dockerfile, then there will be a Warning

  Tips are as follows:

  [Warning] One or more build-args [foo] were not consumed.

We can define one or more parameters, as follows:

  FROM busybox
  ARG user1
  ARG buildno
  ...

  It can also be a default value to the parameter:

  FROM busybox
  ARG user1=someuser
  ARG buildno=1
  ...

  If we give the parameter default values ​​ARG definition, then the parameter value is not specified when the build image, will use the default value

 

ONBUILD

grammar:

  ONBUILD [INSTRUCTION]

  This command takes effect only on the current sub-mirror image.

  Such as the current mirror is A, adding the Dockerfile:

  ONBUILD RUN ls -al

  Time will not start or build in the mirror A ls -al command

  At this time, there is a mirror image B is constructed based on A, then the command is executed ls -al B when the mirror construction.

  

stoplight

grammar:

  STOPSIGNAL signal

  STOPSIGNAL command role when the container is introduced to the system what kind of command transmission

 

 

HEALTHCHECK

   Container health check command

There are two syntax:

  1. HEALTHCHECK [OPTIONS] CMD command
  2. HEALTHCHECK NONE

  The first function is to run a command inside the container to check the health of container

  The second function is to cancel the order on the basis of health checks in the mirror

[OPTIONS] The option supports the following three options:

     --interval = DURATION checked twice default time interval is 30 seconds

     --timeout = DURATION command runs a health check timeout duration, default 30 seconds

     --retries = N when the continuous number of times specified after the failure, then the container is considered to be unhealthy state Unhealthy, default is 3 times

note:

  HEALTHCHECK command can only appear once, if there has been several times, only the last one will work.

  The return value of CMD command behind the decision of this health check is successful, specific return values ​​are as follows:

  0: success - represents a container is healthy

  1: unhealthy - represents a container has been unable to work

  2: reserved - retention

 

example:

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

  Health check command is: curl -f http: // localhost / || exit 1

  Two inspection interval is 5 seconds

  Command timeout time is 3 seconds

Docker-compose.yml

  A standard configuration file should contain version, services, networks of three parts, one of the most critical is the services and networks of two parts, first look at the following services of writing rules.

services:
  web:
    image: hello-world

  In the second stage label label services are web, the name is the user's own custom, it is the service name.
  image is the image name or image ID specified services. If the mirror does not exist locally, Compose will try to pull this image.

The following example formats are possible:

  Image: repeat

  image: ubuntu:14.04

  image: tutum/influxdb

  image: example-registry.com:4000/postgresql

  image: a4bc65fd

 

build

  In addition to the service based on the specified image can also be based on a Dockerfile, at the start up of the implementation of the use of build tasks, the build tag is build, it can specify the path to the folder where Dockerfile. Compose will automatically use it to build the mirror, and then use this image to start the service container.

  build: /path/to/build/dir

  It may be a relative path, as long as it can read the context determination Dockerfile.

  build: ./dir

  Setting context root, and then subject to the specified directory Dockerfile.

build:
  context: ../
  dockerfile: path/of/Dockerfile

  Note build is a directory, if you want to specify Dockerfile files require dockerfile tag in the child tag build label specified, as in the example above.

  If you specify both the image and build two labels, then Compose builds a mirror image and the name of that name back image.

  build: ./dir

  image: webapp:tag

  Since the build tasks can be defined in the docker-compose.yml, then the label must ultimately arg, like Dockerfile the ARG instruction, it can specify an environment variable in the build process, but canceled after a successful build, the docker-compose. yml file also support the wording:

build:
  context: .
  args:
    buildno: 1
    password: secret

  The following such an approach is also supported, in general, the following wording is more suitable for reading.

build:
  context: .
  args:
    - buildno=1
    - password=secret

  The difference is that the ENV, ARG allow null values. E.g:

args:
  - buildno
  - password

  In this way the build process can be assigned to them.

  Note: YAML Boolean values ​​(true, false, yes, no, on, off) must be enclosed in quotation marks (single quotes, double quotes are available), otherwise they will be treated as string parsing.

 

command

  Use command can override the default command is executed after the vessel started.

  command: bundle exec thin -p 3000

  Dockerfile can also be written in a format similar to this:

  command: [bundle, exec, thin, -p, 3000]

container_name

  Compose said before the vessel name format is: <project name> <service name> <number>
  Although you can customize the project name, service name, but if you want full control of the vessel name, you can use this tag specifies:

  container_name: app

  Names such container on the designated app.

 

depends_on

  When using Compose, the biggest advantage is to play a small start-up command, but the order of the general project started by the container is required, if the direct start from top to bottom of the container, because the container will inevitably depend on the issue failed to start.

  For example, when did you start the database container started the application container, the container application at this time because the database can not find the exit, in order to avoid this we need to add a tag is depends_on, the label resolved rely container, has started The problem.

  The following example will first start redis container and db two services, and finally start the web service:

version: '2'
services:
  web:
    build: .
    depends_on:
      - db
      - repeat
  repeat:
    Image: repeat
  db:
    image: postgres

  Note that, when used in this way docker-compose up web start web service by default, will start redis and db two services, because the definition of the dependencies in the configuration file.

 

dns

  --Dns parameters and uses the same format as follows:

  dns: 8.8.8.8

It can also be a list:

dns:
  - 8.8.8.8
  - 9.9.9.9

  In addition dns_search configuration is also similar:

dns_search: example.com
dns_search:
  - dc1.example.com

 

tmpfs

  Mount the temporary directory to the interior of the vessel, as the effect of the parameters run:

tmpfs: /run
tmpfs:
  - /run
  - /tmp

 

entrypoint

  Instructions called a Dockerfile ENTRYPOINT instruction to specify that the access point

  The access point may be defined docker-compose.yml, the cover defined in Dockerfile:

  entrypoint: /code/entrypoint.sh

  Format and Docker similar, but can also be written like this:

entrypoint:
    - php
    - -d
    - zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so
    - -d
    - memory_limit=-1
    - vendor/bin/phpunit

 

env_file

  Remember .env file previously mentioned it, this file can be set Compose variable. In the docker-compose.yml file can be defined in a specialized storage variable.

  If the configuration file specifies docker-compose -f FILE, then the path will be used env_file profile path.

  If there are conflicting instructions environment variable name, the latter shall prevail. Format is as follows:

  env_file: .env

The docker-compose.yml or a plurality of:

env_file:
  - ./common.env
  - ./apps/web.env
  - /opt/secrets.env

  Note that here the environment variable is Compose host of terms, if there is build operations in the configuration file, these variables do not enter the building process, if the variables used to build or just speak in front of choice the arg tag.

 

environment

  And above env_file label completely different, but somewhat similar and arg, the role of this tag is to set up a mirrored variable, it can save variables to a mirror inside, that will start a container that contains these variables are set, and this is arg The biggest difference.

  Arg tag variables are generally only used in the build process. Dockerfile the environment and in the same instruction ENV variable will have been stored in the mirror, a container, a similar effect docker run -e.

environment:
  RACK_ENV: development
  SHOW: 'true'
  SESSION_SECRET:
 environment:
  - RACK_ENV=development
  - SHOW=true
  - SESSION_SECRET

 

expose

  This tag Dockerfile as the EXPOSE command, a designated port is exposed, but only as a reference, in fact, the port mapping docker-compose.yml have ports such labels.

expose:
 - "3000"
 - "8000"

 

external_links

  Docker in the use of the process, we have a bunch of separate docker run to start the container, in order to be able to connect Compose container docker-compose.yml these are not defined, we need a special label is external_links, it allows Compose project inside the vessel is connected to the external configuration of the container that project (for an external container must have at least one container is connected to the same network programs and services within the inside).
Format is as follows:

external_links:
 - redis_1
 - project_db_1:mysql
 - project_db_1:postgresql

 

extra_hosts

  Add the host name of the label is to / etc / hosts file to add some records, and Docker client's --add-host something like:

extra_hosts:
 - "somehost:162.242.195.82"
 - "otherhost:50.31.209.229"

  After starting to see inside the container hosts:

162.242.195.82  somehost
50.31.209.229   otherhost

 

labels

  Adding metadata, and the container Dockerfile a LABEL instruction means, in the following format:

labels:
  com.example.description: "Accounting webapp"
  com.example.department: "Finance"
  com.example.label-with-empty-value: ""
labels:
  - "com.example.description=Accounting webapp"
  - "com.example.department=Finance"
  - "com.example.label-with-empty-value"

 

links

  Remember the above depends_on it, that label is to start to solve the problem of the order, the label is a container solve connection problems with Docker client's --link the same effect, it will connect to other services in the container.
Format is as follows:

links:
 - db
 - db:database
 - repeat

  Alias ​​will automatically use the service container / etc / hosts was created. E.g:

172.12.2.186  db
172.12.2.186  database
172.12.2.187 repeat

  The appropriate environment variables will also be created.

 

logging

This tag is used to configure the logging service. Format is as follows:

logging:
  driver: syslog
  options:
    syslog-address: "tcp://192.168.0.42:123"

  The default driver is json-file. Only json-file and journald can display the log by docker-compose logs, otherwise there are other ways to view the log, but does not support Compose. For optional value can be used to specify options.
For more information in this regard can read the official document: https://docs.docker.com/engine/admin/logging/overview/

 

pid

  pid: "host"

  The PID PID mode is set to host mode, shared with the host system processes namespace. The containers will be able to access and manipulate the tag name space of the host and other containers.

 

ports

Port Mapping tab.
Use HOST: CONTAINER format or just specified container port, port mapping host random chance.

ports:
 - "3000"
 - "8000:8000"
 - "49100:22"
 - "127.0.0.1:8001:8001"

  Note: When using HOST: When CONTAINER port mapping format, if you use a container port less than 60 you might get the wrong results too, because YAML will resolve xx: yy The digital format is 60 decimal. It is recommended that the use of string format.

 

security_opt

  Override the default label for each container. Simply put, all the services that manage labels. All services such as setting user label is USER.

security_opt:
  - label:user:USER
  - label:role:ROLE

  

stop_signal

  Another signal is provided to stop the container. Use the default is SIGTERM to stop the vessel. Another signal may be used provided stop_signal tag.

  stop_signal: SIGUSR1

 

volumes

  A directory or mount an existing data volume container, can be used directly [HOST: CONTAINER] this format, or use [HOST: CONTAINER: ro] this format, the latter to the container, the data volume is read so it can effectively protect the host file system.

  Compose specified path data volume may be a relative path, use. Or .. to specify the relative directory.
  Data volume format may be the following forms:

volumes:
  // just specify a path, Docker will automatically create a data volume (the path is inside the container).
  - / var / lib / mysql
 
  // using an absolute path to mount data volume
  - /opt/data:/var/lib/mysql

  // to Compose profile centered relative to the container as a data path to mount the volume.
  - ./cache:/tmp/cache
 
  // user relative path (directory ~ / represents the / home / <user directory> / or / root /).
  - ~/configs:/etc/configs/:ro

  // existing named data volumes.
  - datavolume:/var/lib/mysql

  If you do not use the path of the host, you can specify a volume_driver.

volume_driver: mydriver
volumes_from  

  Parameter data volume loading or service from another container, optionally: ro or: rw, read only the former represents a container, which represents the data volume of the container is readable and writable. The default is readable and writable.

volumes_from:
  - service_name
  - service_name:ro
  - container:container_name
  - container:container_name:rw

   

cap_add, cap_drop

  Add or delete kernel function of the container.

cap_add:
  - ALL

cap_drop:
  - NET_ADMIN
  - SYS_ADMIN

 

cgroup_parent

  Specify a container parent cgroup.

  cgroup_parent: m-executor-abcd

 

devices

  Device mapping list. Similar to the Docker client's --device parameters.

devices:
  - "/dev/ttyUSB0:/dev/ttyUSB0"

  

extends

This tag can be extended another service, content can be extended from the current file, it can also come from other documents, the case of the same service, and later there will be selectively overwrite the previous one.

extends:
  file: common.yml
  service: webapp

  Users can use this tag at any place, as long as the tag contains the file content and service two values ​​on it. The value of the file can be relative or absolute path, if the value of the file is not specified, Compose will read the information on the current YML file.

network_mode

  Network mode, and parameters Docker client --net similar, but relatively more than a service: [service name] format.
E.g:

network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"

You can specify the use of network services or container.

 

networks

Add the specified network, the following format:

services:
  some-service:
    networks:
     - some-network
     - other-network

  On this label there is a special sub-label aliases, which is used to set a service alias tag, for example:

services:
  some-service:
    networks:
      some-network:
        aliases:
         - alias1
         - alias3
      other-network:
        aliases:
         - alias2

  The same service may have different aliases in different networks.

 

other

  These tags also: cpu_shares, cpu_quota, cpuset, domainname , hostname, ipc, mac_address, mem_limit, memswap_limit, privileged, read_only, restart, shm_size, stdin_open, tty, user, working_dir
label on a single value which are similar to use the effect docker run.

cpu_shares: 73
cpu_quota: 50000
cpuset: 0,1
user: postgresql
working_dir: /code
domainname: foo.com
hostname: foo
ipc: host
mac_address: 02:42:ac:11:65:43
Mem_limit: 1000000000
memswap_limit: 2000000000
privileged: true
restart: always
read_only: true
shm_size: 64M
stdin_open: true
tty: true

  

docker-compose common commands

docker-compose ps to see what the current container (docker-compose.yml folder where the execution)

docker-compose config -q verification (docker-compose.yml) file configuration, when properly configured, does not output anything, when the configuration file error, outputs an error message.

docker-compose restart nginx nginx restart the container services (note the layout file service)

docker-compose logs nginx nginx logs view 

docker-compose logs -f nginx view real-time log of nginx

docker-compose up 

docker-compose down

docker-compose exec nginx bash into the container under nginx Service

docker-compose exec --index = 1 nginx bash parameters need to add more than one container --index enters the service nginx = xxx

Guess you like

Origin www.cnblogs.com/ajunyu/p/12320761.html