Docker Containerization Guide: Installation, Configuration, and Management
Installing Docker Community Edition
For installation instructions, refer to the official Aliyun Docker CE repository:
Using the official installation script (only for public network environments):
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
For CentOS 7 installation using yum:
# Install required system tools
sudo yum install -y yum-utils device-mapper-persistent-data lvm2
# Add repository information
sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# Update and install Docker CE
sudo yum makecache fast
sudo yum -y install docker-ce
# Start Docker service
systemctl start docker
# Check Docker version
docker version
# Enable auto-start on boot
systemctl enable docker
Configuring Docker Registry Mirrors
For configuring registry mirrors, refer to Aliyun Container Registry console:
curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://f1361db2.m.daocloud.io
sudo systemctl daemon-reload
sudo systemctl restart docker
Essential Docker Commands
# View running containers
docker ps
# View all containers (including stopped ones)
docker ps -a
# Pull an image from registry
docker pull [image_name]
# List local images
docker images
# Create a container (returns container ID)
docker create nginx
# Start a container
docker start [container_id]
# Restart a container
docker restart [container_id]
# Run a container (pulls image if not exists, then creates and starts)
docker run hello-world
# Run in detached mode
docker run -d [image_name]
# Port mapping (host_port:container_port)
docker run -p [host_port]:[container_port] [image_name]
# CPU share allocation
docker run -c [cpu_share] [image_name]
# Volume mapping (host_path:container_path)
docker run -v [host_path]:[container_path] [image_name]
# Memory limit
docker run -m [memory_limit] [image_name]
# Memory swap limit
docker run --memory-swap [swap_limit] [image_name]
# IO weight
docker run --blkio-weight [io_weight] [image_name]
# Set container name
docker run --name [container_name] [image_name]
# Restart policy
docker run --restart=[policy] [image_name]
# Policy options: no, on-failure, always
# Pause a container
docker pause [container_id]
# Unpause a container
docker unpause [container_id]
# Stop a container
docker stop [container_id]
# Remove a container (cannot remove running containers)
docker rm [container_id]
# Force remove a container
docker rm -f [container_id]
# View container logs
docker logs [container_id]
# Follow container logs
docker logs -f [container_id]
# Interact with container using bash
docker exec -it [container_id] /bin/bash
Batch Operations
# Stop all running containers
docker stop $(docker ps -q)
# Remove all containers
docker rm $(docker ps -aq)
# Remove all images
docker rmi $(docker images -q)
# Remove images by condition
# Remove untagged images
docker rmi $(docker images -q | awk '/^<none>/ { print $3 }')
# Remove images with keyword (replace 'xxx' with your keyword)
docker rmi --force $(docker images | grep xxx | awk '{print $3}')
# Restart exited containers
docker restart $(docker ps -a|grep Exited|awk '{print $1}')
# Clean build cache
docker builder prune -f
Running Common Applications
# Start Redis as a service
docker run -d --name myredis -p 6379:6379 redis redis-server
# Interact with Redis CLI
docker exec -it [container_id] redis-cli
# Run RabbitMQ with management plugin
docker run -d --name myrabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:management
# Deploy MySQL
docker run -d --name mymysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=your_password mysql
# Run Nginx with frontend code mapping
docker run -d --name mynginx -p 80:80 -v /path/to/frontend:/usr/share/nginx/html nginx
# Nginx with custom configuration
docker run \
-d \
-p 82:80 \
--restart=always \
-v ~/nginx/conf.d:/etc/nginx/conf.d \
-v ~/nginx/logs:/var/log/nginx \
nginx:1.21.6
# Deploy ELK stack
docker pull sebp/elk
docker run -p 5601:5601 -p 9200:9200 -p 5044:5044 -e ES_MIN_MEM=128m -e ES_MAX_MEM=1024m -d --name elk sebp/elk
# Fix max_map_count issue
# Edit sysctl.conf
echo "vm.max_map_count=262144" >> /etc/sysctl.conf
sysctl -p
# Enter container
docker exec -it [container_id] /bin/bash
# Modify Logstash configuration
# File location: /etc/logstash/conf.d/02-beats-input.conf
# Replace content with:
input {
tcp {
port => 5044
codec => _lines
}
}
output{
elasticsearch {
hosts => ["localhost:9200"]
}
}
# Restart container (wait 5-10 minutes for services to restart)
docker restart elk
# Access Kibana
http://localhost:5601/
Working with Dockerfiles
Each instruction in a Dockerfile creates a new layer in the Docker image. To minimize image size, combine commands using the && operator to create only one layer.
# Create Dockerfile
vim Dockerfile
# Sample Dockerfile:
# Comments
# Base image for the custom image
FROM debian
# Run commands
# Shell format: RUN <command>
# Exec format: RUN ["executable", "param1", "param2"]
RUN echo 'Build process started' && mkdir /app
# Copy files from context to container
COPY source_file /app/
# ADD automatically extracts compressed files
ADD archive.tar.gz /app/
# Define volume for data persistence
VOLUME /data
# Command to run when container starts (can be overridden)
CMD ["-c", "ls -l"]
# Entrypoint (cannot be overridden, parameters are passed to the command)
ENTRYPOINT ["/bin/sh"]
# Expose port
EXPOSE 8083
# Build image -t specifies name and tag
docker build -t myimage .
# Run image
docker run myimage
# Override CMD command
docker run myimage -c date
Docker Compose
Download and install Docker Compose
curl -L https://get.daocloud.io/docker/compose/releases/download/v2.2.3/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
Offline Import and Export
# Export container as image file
docker export [container_id] > container_export.tar
# Import image
docker import - new_image_name < container_export.tar
# Save image with metadata
docker save [image_id] > image_save.tar
# Save multiple images
docker save -o images.tar postgres:9.6 mongo:3.4
# Load image
docker load < image_save.tar
Differences Between Export/Import and Save/Load
- These methods are not interchangeable. Using import with a save-generated file will result in container startup failures.
- Export produces smaller files than save
- Import allows specifying a new name, load does not
- Export cannot package multiple images, save can
- Export loses image history and metadata, save preserves it
- Export use case: Creating base images from modified containers
- Save use case: Offline deployment of multi-container applications
Offline Docker Installation
Download Docker binaries from:
Docker Service Configuration
# docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target
[Service]
Type=notify
ExecStart=/usr/bin/dockerd
ExecReload=/bin/kill -s HUP $MAINPID
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TimeoutStartSec=0
Delegate=yes
KillMode=process
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s
[Install]
WantedBy=multi-user.target
Installation Script
#!/bin/sh
# Install Docker
tar -xvf docker-20.10.14.tgz
cp docker/* /usr/bin/
cp docker.service /etc/systemd/system/
chmod +x /etc/systemd/system/docker.service
systemctl daemon-reload
systemctl start docker
# Create Docker daemon configuration
cat <<EOF > /etc/docker/daemon.
{
"registry-mirrors": [
"https://docker.1ms.run",
"https://docker.xuanyuan.me"
],
"exec-opts": ["native.cgroupdriver=systemd"],
"log-driver": "-file",
"log-opts": {
"max-size": "100m",
"max-file": "3"
},
"storage-driver": "overlay2"
}
EOF
systemctl enable docker
systemctl daemon-reload
systemctl restart docker
docker -v
echo 'Docker installation successful...'
# Install Docker Compose
cp docker-compose-linux-x86_64 /usr/bin/docker-compose
chmod +x /usr/bin/docker-compose
docker-compose -v
echo 'Docker Compose installation successful...'
Uninstallation Script
#!/bin/sh
echo 'Removing docker.service...'
rm -f /etc/systemd/system/docker.service
echo 'Removing Docker files...'
rm -rf /usr/bin/docker*
echo 'Reloading configuration...'
systemctl daemon-reload
echo 'Uninstallation complete...'
Troubleshooting Common Issues
IPv4 Forwarding Disabled
# On the host machine
echo "net.ipv4.ip_forward=1" >> /usr/lib/sysctl.d/00-system.conf
# Restart network and docker services
systemctl restart network && systemctl restart docker
Accessing Container as Root
# Run container with privileged flag
docker run -d -p 8888:8888 --privileged=true [image_name]
# Enter container as root
docker exec -it -u root [container_id] /bin/bash
Non-root User Docker Access
# Add user to docker group
sudo usermod -aG docker [username]
File Descriptor Allocation Error
# Issue on older machines or ARM-based servers
# Check systemctl version
systemctl --version
# Fix by modifying /lib/systemd/system/docker.service
# Change:
LimitCORE=infinity
LimitNOFILE=infinity
LimitNPROC=infinity
# To:
LimitCORE=65535
LimitNOFILE=65535
LimitNPROC=65535
# Restart docker service
systemctl restart docker
MySQL Data Import/Export
# Find MySQL container ID
docker ps
# Enter MySQL container
docker exec -it [container_id] bash
# Export database (enter MySQL password when prompted)
mysqldump -u root -p [database_name] > dump.sql
# Note export file location
pwd
# Exit container
exit
# Copy file from container to host
docker cp [container_id]:dump.sql ~/
# Copy local file to container
docker cp /path/to/local/file.sql [container_id]:/path/in/container/file.sql
# Enter MySQL container
docker exec -it [container_id] bash
# Import database
mysql -u root -p [database_name] < /path/in/container/file.sql
Image Packaging Script
#!/bin/bash
# Associative array for image management
declare -A image_map
# Define directory for saving images
save_dir="/path/to/save/images"
# Ensure save directory exists
mkdir -p "$save_dir"
# Define array of images to process
images=(
"registry.example.com/project:version1"
"registry.example.com/project:version2"
)
# Pull and save each image
for image in "${images[@]}"
do
# Create filename from image name
filename=$(echo "$image" | sed 's|registry.example.com/project/||' | sed 's|:|-|' | sed 's|$|.tar|')
save_path="${save_dir}/${filename}"
echo "Processing image: $image → $save_path"
# Pull image
docker pull "$image"
# Save image to tar file
docker save "$image" -o "$save_path"
echo "Image saved: $save_path"
done
echo "All images processed successfully."