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 containerSHELL
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/