Docker——一個容器平臺
Docker
Concepts
docker images
A Docker image is an immutable (unchangeable) file that contains the source code, libraries, dependencies, tools, and other files needed for an application to run.
docker containers
A Docker container is a virtualized run-time environment where users can isolate applications from the underlying system.
Commands
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
# 搜尋映象 docker search xxx #列舉映象 docker images #下載映象 docker pull NAME[:TAG] #刪除映象 remove images docker rmi IMAGE1 IMAGE2... docker image rm IAMGE1 IMAGE2... #列舉所有執行的容器 docker ps -a # list running containers docker container ls # list all containers docker container ls -a # start a container docker container start <container-id/name> # remove a container docker rm CONTAINER # exec command in a container, #相當於以額外程序進入,從中exit不會導致容器被關閉 docker exec -it <continaer-id/name> /bin/bash # show container id inside itself (for a linux container) cat /proc/self/cgroup # executed inside the container # docker run # create a new container from an image then run it # -d: daemon docker run -d -it -p <host-port:container-port> IMAGE ARGS... OPTIONS: -d: dettach (run in background) -p HOST_PORT:CONTAINER_PORT : port mapping -v HOST_PATH:CONTAINER_PORT[:VOPTIONS] : volumes (shared files) VOPTIONS: `ro`,`rw` -i: keep STDIN open -t: allocate a pseudo tty docker run -d -p 8080:80 -p 8081:81 -v /home/me/html:/usr/share/nginx/html:ro -v /home/me/data:/data:rw --name my_container_name CONTAINER # attach to a container docker attach <container-id/name> # attach to 相對於docker exec,attach是進入主控制,從中exit會導致容器被關閉 # dettach from a container docker dettach <container> # dettach from #拷貝檔案,宿主機<->容器兩種方向間的拷貝命令均在宿主機中執行(宿主機中才有docker命令) # host -> container docker cp /path/source/in/host <container-id/name>:/path/destination # container -> host docker cp <container-id/name>:/path/source /path/destination/in/host # copy files between containers <-- NOT supported docker commit <container> IMG:TAG #提交修改到本地映象(或新建映象) #如果對容器的修改未被提交,則容器被關閉後其修改將丟失 # show logs docker logs [OPTIONS] CONTAINER -f: follow --tail N: tail N lines -n N: same to --tail N --details: show extra details -t, --timestamps: show timestamps --since TIME: since time, e.g. 2050-01-01T00:00:00, 30m(for 30 minutes) --until TIME # create another name&tag for given source image, the source can be given by SHA ID or name docker tag SORUCE[:TAG] TARGET[:NAME] # push an image to remote docker push IMAGE_NAME # the remote registry is detected from IMAGE_NAME, formatted [REGISTRY/]REPO/ARTIFACT[:TAG] # the default registry, the official docker hub, will be used if [REGISTRY] part of IMAGE_NAME is missing. # if we want to push an image without [REGISTRY] in its name to specified registry, we should create a tag with image name explicitly containing REGISTRY using command `docker tag SOURCE[:TAG] REGISTRY/REPO/ARTIFACT[:TAG]`, then we push the newly created tag # remove all images named '<none>' docker images |grep '^<none>'|tr -s ' ' | cut -d\ -f3|xargs docker rmi -f
可以將容器中的目錄掛載到宿主機的目錄(docker run -v)。
Configuration
Run docker without sudo
create a group docker
, and add working user($USER) into it.
sudo groupadd docker
sudo usermod -aG docker $USER
docker hello world:
docker --version
# docker pull hello-world
docker run hello-world
Attach volumes to an existing container
It needs restarting the docker service, so it can NOT attach to an running container without stopping it.
Steps:
- edit the
"MountPoints"
section of the config file of the container. the config file is located at/var/lib/docker/containers/<container-id>/config.v2.json
an exmaple for MountPoints:
{
"MountPoints": {
"/mnt": {
"Source": "/path/in/host/os",
"Destination": "/mnt",
"RW": true,
"Name": "",
"Driver": "",
"Type": "bind",
"Propagation": "rprivate",
"Spec": {
"Type": "bind",
"Source": "/path/in/host/os",
"Target": "/mnt"
},
"SkipMountpointCreation": false
}
}
}
- restart the docker service
systemctl restart docker.service
DNS
you can config default dns in the /etc/docker/daemon.json
(see the section configuration), or options from creating a container (docker run --dns ... --dns-options ... --dns-search ...
).
Reassign port to an existing container
- stop container
- edit
Config/Ports
part in the config file of the container, located at/var/lib/docker/containers/<ID>/config.v2.json
- restart docker service:
systemctl restart docker
- start container
GUI Applications
For an x-term user, you can achieve the ability of GUI application supporting by following steps:
- share XServer authority
- share env DISPLAY
- use host net
docker run --net=host --volume="$HOME/.Xauthority:/root/.Xauthority:rw" --env="DISPLAY" IMAGE
Anatomy of docker Image: base image, parent image, image layer, container layer, manifest.
Docker Image Layer
A docker layer is a intermediate container(image) that contains a sequence of docker instructions for helping to create a docker image.
Build Images
Build images from command line terminal:
docker build -t IAMGE_NAME PATH
, where the PATH
containing Dockerfile
and data.
multi-stage building
An exmaple of instructions for multi-stage building:
FROM xxx AS my_stage_name1
...
FROM xxx AS my_stage_name2
...
FROM my_stage_name1 AS my_stage_name3
...
reference names for name-undefined stages are numbers, i.e. 0, 1, ....
build images stopping at a specified stage:
docker build --target STAGE_NAME -t NEW_IMAGE_NAME
Dockerfile
Instructions:
FROM
RUN
-
COPY
to copy from specified image; copy from host.COPY ./src-dir /dest # this will copy all items under /some-dir, into /dest, which will NOT create the directory 'some-dir'. e.g. /src-dir/* --> /dest/* insdead of /dest/src-dir/* COPY ./src-dir/. /dest # src-dir/* --> /dest/src-dir/*
CMD
ENTRYPOINT
-
WORKDIR
setting working directory for subsequenct instructions of Dockerfile. the target directory will be created if not existing even if it's not used in subsequenct instructions. EXPOSE
-
HEALTHCHECK
to define a method to check the health status of the running container -
SHELL
to define the default shell for the following CMD/RUN/ENTRYPOINT etc. instructions
FROM microsoft/windowsservercore
# Executed as cmd /S /C echo default
RUN echo default
# Executed as cmd /S /C powershell -command Write-Host default
RUN powershell -command Write-Host default
# Executed as powershell -command Write-Host hello
SHELL ["powershell", "-command"]
RUN Write-Host hello
# Executed as cmd /S /C echo hello
SHELL ["cmd", "/S", "/C"]
RUN echo hello
STOPSIGNAL
Each instruction is run independently and causes a new image to be created. So RUN cd /tmp
will not have any effect on next instructions.
Compose
Compose is a tool for defining and running multi-container Docker applications. A YAML file is used to configure the application services to run.
Docker Registry
open source under Apache license on github: docker/distribution
To host docker images.
Global public docker registry: Docker Hub
open source registry providers
Install
On Ubuntu 16.04
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
#如果網路無法連線,可手動FQ下載該檔案,或curl -x proxyHost:port ...
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt update
apt-cache policy docker-ce
#有以下輸出為成功 500 http://....
#有以下輸出為失敗 docker-ce: 已安裝:(無) 候選: (無) 版本列表:
sudo apt install -y docker-ce
On CentOS 6.x
Since CentOS 6.x is not maintained, we can not install by command yum install docker-io
. We can install an older version of docker engine.
# downlaod .rpm package
wget https://get.docker.com/rpm/1.7.0/centos-6/RPMS/x86_64/docker-engine-1.7.0-1.el6.x86_64.rpm
yum install docker-engine*.rpm
# or
rpm -i --nodeps docker-engine*.rpm
配置倉庫國內映象:
在檔案/etc/docker/daemon.json
中加入:
{
"registry-mirrors": ["https://docker.mirrors.ustc.edu.cn/"]
}
docker倉庫國內映象地址:
中科大(免賬號直接使用):https://docker.mirrors.ustc.edu.cn/ (幫助)
阿里雲(註冊開發賬號後可用):https://cr.console.aliyun.com/#/accelerator
禁止docker服務隨作業系統啟動而啟動:
sudo systemctl disable docker
配置隨作業系統啟動而啟動(start on boot):
sudo systemctl enable docker
(手動)開啟服務:
sudo systemctl start docker
#或
#sudo service docker start
關停服務:
sudo systemctl stop docker
#或
#sudo service docker stop
Configuration
- edit configuration file,
/etc/docker/daemon.json
{
# Configure network subnet range
"bip":"172.16.0.1/16",
# default dns (if not configured the docker will fall back to the 8.8.8.8+4.4.4.4)
"dns":["114.114.114.114","8.8.8.8","4.4.4.4"]
}
the bip
, binding network bridge, is a configuration for network subnet range, whose the last digit can NOT be 0, i.e. can NOT be like x.x.x.0
.
2) restart server
sudo systemctl restart docker
FAQ
[ERROR]: Failed to start Docker Application Container Engine, failed to allocate network, address already in use.
check the configuration bip
in /etc/docker/daemon.json
, which should not end with 0 (not be like x.x.x.0/<mask>
); it can be 'x.x.x.1/