Skip to main content
Version: 1.0

Guide

Docker helps developers bring their ideas to life by conquering the complexity of app development.

Tutorial

Install Docker

You can install Docker and Compose by official script below if you have not install them:

curl -fsSL https://get.docker.com -o get-docker.sh && sh get-docker.sh
curl -L "https://github.com/docker/compose/releases/download/1.29.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
ln -sf /usr/local/bin/docker-compose /usr/bin
sudo systemctl start docker

Set Docker Registry in China

If you want to speed you docker image pull, you should set your Docker Registry:

  1. Select your Docker Registry accelerated URL of China

    #1 Docker china community
    https://registry.docker-cn.com

    #2 162 mirror
    http://hub-mirror.c.163.com

    #3 Tencent mirror
    https://mirror.ccs.tencentyun.com
  2. Modify your /etc/docker/daemon.json and add the below paragraph to it

    # Single URL
    {
    "registry-mirrors": ["http://hub-mirror.c.163.com"]
    }

    # Multiple URL
    {
    "registry-mirrors": ["https://registry.docker-cn.com","https://docker.mirrors.ustc.edu.cn","http://hub-mirror.c.163.com"]
    }
  3. Save and restart your Docker service

    sudo systemctl daemon-reload
    sudo systemctl restart docker

Enable Docker API

By default, docker API just access by local socket

curl --unix-socket /var/run/docker.sock  http://docker/version

If you want to enable remote Docker API, you should modify [Docker system service].

ExecStart=/usr/bin/dockerd -H fd://   --containerd=/run/containerd/containerd.sock -H tcp://0.0.0.0:2375

Check Service in Docker

You should know that we can't use systemctl command in Container, but you can use service command in Container

# check all service at Container
service --status-all

# Manage service at Container
service apache2 start | status | stop | restart

Recreate Docker

cd /data/apps/appname
docker-compose down -v
docker-compose pull
docker-compose up -d

Upgrade single container

Take the MySQL container as an example to show the upgrade steps:

# upgrade MySQL Docker image
docker pull mysql

# stop your MySQL container
docker stop my-mysql-container

# delete your MySQL container
docker rm my-mysql-container

# Recreate your MySQL container use previous data
docker run --name=my-mysql-container --restart=always -e MYSQL_ROOT_PASSWORD=mypwd -v /path/data/dir:/var/lib/mysql -d mysql

Upgrade multiply container

If you use Compose for multiply container, upgrade is very easy:

docker-compose down -v
docker-compose pull
docker-compose up -d

Troubleshoot

Can't access application of container?

There are three possible reasons for this problem:

  1. The port mapping is set incorrectly, causing the container to have no network
  2. The container does not have remote access
  3. The port is not enabled at Security Group

docker-containerd.socket: timeout?

You should disable your SElinux before running Docker

Docker can't start at Windows?

Please make sure you have not install any security software on Windows

Parameters

Path

Docker root directory: /var/lib/docker
Docker image directory: /var/lib/docker/image
Docker daemon.json: please create it when you need and save to to the directory /etc/docker
Docker systemd service: /lib/systemd/system/docker.service

Port

You should set port for Docker API

Version

# Docker Version
docker -v

Service

These commands you must know when you using the Websoft9

Docker

sudo systemctl start docker
sudo systemctl restart docker
sudo systemctl stop docker
sudo systemctl status docker

Docker-Compose

# Create multiply container
sudo docker-compose up

# Create multiply container at backend
sudo docker-compose up -d

# Mange all containers
sudo docker-compose start
sudo docker-compose stop
sudo docker-compose restart

Docker container

The stop command will release system resource of container but not delete it

# e.g: mysql
sudo docker pause mysql
sudo docker stop mysql

# e.g: redis
sudo docker pause redis
sudo docker stop redis

CLI

These commands is for you to manage Docker

systemctl start/stop docker     #start/stop docker service
systemctl enable docker #enable docker running when OS start
docker pull #pull Docker image
docker ps #list all running Containers
docker ps -a #list all Containers
docker start/stop CONTAINER ID #start/stop Container
docker rm CONTAINER ID #delete Container by ID
docker kill CONTAINER ID #shut down Container
docker images #list all images have been downloaded

Docker

Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

Options:
--add-host list Add a custom host-to-IP mapping (host:ip)
-a, --attach list Attach to STDIN, STDOUT or STDERR
--blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
--blkio-weight-device list Block IO weight (relative device weight) (default [])
--cap-add list Add Linux capabilities
--cap-drop list Drop Linux capabilities
--cgroup-parent string Optional parent cgroup for the container
--cgroupns string Cgroup namespace to use (host|private)
'host': Run the container in the Docker host's cgroup namespace
'private': Run the container in its own private cgroup namespace
'': Use the cgroup namespace as configured by the
default-cgroupns-mode option on the daemon (default)
--cidfile string Write the container ID to the file
--cpu-period int Limit CPU CFS (Completely Fair Scheduler) period
--cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota
--cpu-rt-period int Limit CPU real-time period in microseconds
--cpu-rt-runtime int Limit CPU real-time runtime in microseconds
-c, --cpu-shares int CPU shares (relative weight)
--cpus decimal Number of CPUs
--cpuset-cpus string CPUs in which to allow execution (0-3, 0,1)
--cpuset-mems string MEMs in which to allow execution (0-3, 0,1)
-d, --detach Run container in background and print container ID
--detach-keys string Override the key sequence for detaching a container
--device list Add a host device to the container
--device-cgroup-rule list Add a rule to the cgroup allowed devices list
--device-read-bps list Limit read rate (bytes per second) from a device (default [])
--device-read-iops list Limit read rate (IO per second) from a device (default [])
--device-write-bps list Limit write rate (bytes per second) to a device (default [])
--device-write-iops list Limit write rate (IO per second) to a device (default [])
--disable-content-trust Skip image verification (default true)
--dns list Set custom DNS servers
--dns-option list Set DNS options
--dns-search list Set custom DNS search domains
--domainname string Container NIS domain name
--entrypoint string Overwrite the default ENTRYPOINT of the image
-e, --env list Set environment variables
--env-file list Read in a file of environment variables
--expose list Expose a port or a range of ports
--gpus gpu-request GPU devices to add to the container ('all' to pass all GPUs)
--group-add list Add additional groups to join
--health-cmd string Command to run to check health
--health-interval duration Time between running the check (ms|s|m|h) (default 0s)
--health-retries int Consecutive failures needed to report unhealthy
--health-start-period duration Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
--health-timeout duration Maximum time to allow one check to run (ms|s|m|h) (default 0s)
--help Print usage
-h, --hostname string Container host name
--init Run an init inside the container that forwards signals and reaps processes
-i, --interactive Keep STDIN open even if not attached
--ip string IPv4 address (e.g., 172.30.100.104)
--ip6 string IPv6 address (e.g., 2001:db8::33)
--ipc string IPC mode to use
--isolation string Container isolation technology
--kernel-memory bytes Kernel memory limit
-l, --label list Set meta data on a container
--label-file list Read in a line delimited file of labels
--link list Add link to another container
--link-local-ip list Container IPv4/IPv6 link-local addresses
--log-driver string Logging driver for the container
--log-opt list Log driver options
--mac-address string Container MAC address (e.g., 92:d0:c6:0a:29:33)
-m, --memory bytes Memory limit
--memory-reservation bytes Memory soft limit
--memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap
--memory-swappiness int Tune container memory swappiness (0 to 100) (default -1)
--mount mount Attach a filesystem mount to the container
--name string Assign a name to the container
--network network Connect a container to a network
--network-alias list Add network-scoped alias for the container
--no-healthcheck Disable any container-specified HEALTHCHECK
--oom-kill-disable Disable OOM Killer
--oom-score-adj int Tune host's OOM preferences (-1000 to 1000)
--pid string PID namespace to use
--pids-limit int Tune container pids limit (set -1 for unlimited)
--platform string Set platform if server is multi-platform capable
--privileged Give extended privileges to this container
-p, --publish list Publish a container's port(s) to the host
-P, --publish-all Publish all exposed ports to random ports
--pull string Pull image before running ("always"|"missing"|"never") (default "missing")
--read-only Mount the container's root filesystem as read only
--restart string Restart policy to apply when a container exits (default "no")
--rm Automatically remove the container when it exits
--runtime string Runtime to use for this container
--security-opt list Security Options
--shm-size bytes Size of /dev/shm
--sig-proxy Proxy received signals to the process (default true)
--stop-signal string Signal to stop a container (default "SIGTERM")
--stop-timeout int Timeout (in seconds) to stop a container
--storage-opt list Storage driver options for the container
--sysctl map Sysctl options (default map[])
--tmpfs list Mount a tmpfs directory
-t, --tty Allocate a pseudo-TTY
--ulimit ulimit Ulimit options (default [])
-u, --user string Username or UID (format: <name|uid>[:<group|gid>])
--userns string User namespace to use
--uts string UTS namespace to use
-v, --volume list Bind mount a volume
--volume-driver string Optional volume driver for the container
--volumes-from list Mount volumes from the specified container(s)
-w, --workdir string Working directory inside the container

Docker Compose

$docker-compose -h

Define and run multi-container applications with Docker.

Usage:
docker-compose [-f <arg>...] [--profile <name>...] [options] [--] [COMMAND] [ARGS...]
docker-compose -h|--help

Options:
-f, --file FILE Specify an alternate compose file
(default: docker-compose.yml)
-p, --project-name NAME Specify an alternate project name
(default: directory name)
--profile NAME Specify a profile to enable
-c, --context NAME Specify a context name
--verbose Show more output
--log-level LEVEL Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
--ansi (never|always|auto) Control when to print ANSI control characters
--no-ansi Do not print ANSI control characters (DEPRECATED)
-v, --version Print version and exit
-H, --host HOST Daemon socket to connect to

--tls Use TLS; implied by --tlsverify
--tlscacert CA_PATH Trust certs signed only by this CA
--tlscert CLIENT_CERT_PATH Path to TLS certificate file
--tlskey TLS_KEY_PATH Path to TLS key file
--tlsverify Use TLS and verify the remote
--skip-hostname-check Don't check the daemon's hostname against the
name specified in the client certificate
--project-directory PATH Specify an alternate working directory
(default: the path of the Compose file)
--compatibility If set, Compose will attempt to convert keys
in v3 files to their non-Swarm equivalent (DEPRECATED)
--env-file PATH Specify an alternate environment file

Commands:
build Build or rebuild services
config Validate and view the Compose file
create Create services
down Stop and remove resources
events Receive real time events from containers
exec Execute a command in a running container
help Get help on a command
images List images
kill Kill containers
logs View output from containers
pause Pause services
port Print the public port for a port binding
ps List containers
pull Pull service images
push Push service images
restart Restart services
rm Remove stopped containers
run Run a one-off command
scale Set number of containers for a service
start Start services
stop Stop services
top Display the running processes
unpause Unpause services
up Create and start containers
version Show version information and quit

Template

docker-compose template

services:
frontend:
image: awesome/webapp
ports:
- "443:8043"
networks:
- front-tier
- back-tier
configs:
- httpd-config
secrets:
- server-certificate

backend:
image: awesome/database
volumes:
- db-data:/etc/data
networks:
- back-tier
profiles:
- test

volumes:
db-data:
driver: flocker
driver_opts:
size: "10GiB"

configs:
httpd-config:
external: true

secrets:
server-certificate:
external: true

networks:
# The presence of these objects is sufficient to define them
front-tier: {}
back-tier: {}

dockerfile template

# syntax=docker/dockerfile:1
FROM golang:1.16-alpine AS build

# Install tools required for project
# Run `docker build --no-cache .` to update dependencies
RUN apk add --no-cache git
RUN go get github.com/golang/dep/cmd/dep

# List project dependencies with Gopkg.toml and Gopkg.lock
# These layers are only re-built when Gopkg files are updated
COPY Gopkg.lock Gopkg.toml /go/src/project/
WORKDIR /go/src/project/
# Install library dependencies
RUN dep ensure -vendor-only

# Copy the entire project and build it
# This layer is rebuilt when a file changes in the project directory
COPY . /go/src/project/
RUN go build -o /bin/project

# This results in a single layer image
FROM scratch
COPY --from=build /bin/project /bin/project
ENTRYPOINT ["/bin/project"]
CMD ["--help"]