Master Docker: From Basics to Advanced Container Management
This comprehensive guide explains Docker's origins, core concepts, advantages, installation steps, essential commands, container lifecycle management, image customization with Dockerfile, and publishing to both Docker Hub and private registries, providing practical examples and code snippets for hands‑on learning.
1. Introduction
1.1 What is Docker
Docker was originally an internal project started by Solomon Hykes of dotCloud in France and was open‑sourced in March 2013 under the Apache 2.0 license, with its source code hosted on GitHub.
Docker is written in the Go language released by Google.
Docker is a type of Linux container packaging that provides a simple, easy‑to‑use container interface and is the most popular Linux container solution.
Docker’s interface is very simple, allowing users to easily create and destroy containers.
Docker packages an application together with its dependencies into a single file; running this file creates a virtual container.
Applications run inside the virtual container as if they were on a real physical machine, eliminating environment‑related concerns.
1.2 Application Scenarios
Automated packaging and deployment of web applications
Automated testing, continuous integration and delivery
Deploying and adjusting databases or other services in a service‑oriented environment
1.3 Differences
1. Physical Machine
2. Virtual Machine
3. Docker Container
1.4 Docker’s Three Core Concepts and Advantages
Image
Container
Repository
Docker Container Advantages
1. Higher resource efficiency
Because containers do not require hardware virtualization or a full operating system, Docker utilizes system resources more efficiently, offering faster execution, lower memory consumption, and higher file‑system throughput compared with traditional VMs.
2. Faster startup time
Containers start in seconds or milliseconds because they run directly on the host kernel without booting a full OS, greatly reducing development, testing, and deployment cycles.
3. Consistent runtime environment
Docker images encapsulate the complete runtime environment (excluding the kernel), ensuring that code runs identically across development, testing, and production, eliminating “works on my machine” issues.
4. Continuous delivery and deployment
Developers can build custom images with Dockerfile and integrate them into CI pipelines; operations can deploy these images instantly, and the same Dockerfile serves both teams for transparent configuration.
5. Easier migration
Docker guarantees environment consistency across physical machines, VMs, public or private clouds, and even laptops, allowing seamless migration without compatibility concerns.
2. Docker Installation
System requirements: Docker supports CentOS 7+ on 64‑bit platforms with kernel version 3.10 or higher.
Versions: Community Edition and Enterprise Edition (the latter includes paid features).
https://docs.docker.com/install/linux/docker-ce/centos/#upgrade-docker-after-using-the-convenience-script
Community installation script:
# Install docker
yum install docker
# Start docker
systemctl start/status docker
# Verify Docker version
docker versionConfigure accelerator
DaoCloud accelerator speeds up Docker Hub access in China by using CDN and protocol optimizations.
https://www.daocloud.io/mirror#accelerator-doc
# One‑line accelerator setup (restart Docker afterwards)
curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://95822026.m.daocloud.io3. Basic Docker Commands
Run docker --help for a full list (Chinese annotations shown).
Usage:
docker [OPTIONS] COMMAND [arg...]
Options:
--config=~/.docker Location of client config files
-D, --debug=false Enable debug mode
-H, --host=[] Daemon socket(s) to connect to
-h, --help=false Print usage
-l, --log-level=info Set the logging level
--tls=false Use TLS; implied by --tlsverify
--tlscacert=~/.docker/ca.pem Trust certs signed only by this CA
--tlscert=~/.docker/cert.pem Path to TLS certificate file
--tlskey=~/.docker/key.pem Path to TLS key file
--tlsverify=false Use TLS and verify the remote
-v, --version=false Print version information and quit
Commands:
attach Attach to a running container
build Build an image from a Dockerfile
commit Create a new image from a container's changes
cp Copy files/folders from a container to the host or STDOUT
create Create a new container (does not start it)
diff Inspect changes on a container's filesystem
exec Run a command in a running container
... (other commands omitted for brevity) ...3.1 Two Ways to Start a Container
Containers need a base OS image to run.
1. Create and start a container from an image:
# Run a container in background
docker run -d centos /bin/sh -c "while true; do echo Running; sleep 1; done"
# Check container processes
docker ps
# View logs continuously
docker logs -f <container_id>
# Stop container
docker stop centos2. Start an interactive bash terminal:
docker run --name mydocker -it centos /bin/bashWhen docker run creates a container, Docker performs the following steps:
Check if the specified image exists locally; if not, pull it from a public registry. Create and start a container from the image. Mount a writable layer on top of the read‑only image layer. Bridge a virtual network interface from the host bridge to the container. Assign an IP address from the address pool to the container. Execute the user‑specified application. Terminate the container when execution finishes.
2. Restart a stopped container:
# List all containers (including stopped)
docker ps -a
# Restart a specific container
docker start <container_id>
# Enter the container interactively
docker exec -it <container_id> /bin/bash3.2 Commit to Create a Custom Image
# Enter an interactive CentOS container
docker run -it centos
# Install vim inside the container
yum install -y vim
# Exit the container
exit
# List container records
docker container ls -a
# Commit the container as a new image
docker commit <container_id> myrepo/centos-vim
# Verify the new image
docker images3.3 Expose Container to External Access
Use -p or -P to map container ports to the host.
# Random port mapping
docker run -d -P training/webapp python app.py
# Check mapped port
docker ps -l
# Fixed port mapping
docker run -d -p 9000:5000 training/webapp python app.pyAccess the service via http://<host_ip>:9000 to see "Hello world!".
4. Customizing Images with Dockerfile
A Dockerfile is a plain‑text file containing a sequence of instructions; each instruction creates a new image layer.
Using a Dockerfile allows you to script every modification, installation, and configuration step for reproducible image builds.
FROM centos
LABEL version="1.0"
LABEL maintainer="[email protected]"
RUN yum update && yum install -y vim python-dev \
&& /bin/bash -c "source $HOME/.bashrc; echo $HOME"
WORKDIR /root
ADD hello / # Add local executable to root
COPY hello /test/ # Equivalent COPY example
ENV MYSQL_VERSION 5.6
RUN yum install -y mysql-server=${MYSQL_VERSION}Key Dockerfile instructions:
FROM : Base image
LABEL : Metadata
RUN : Execute commands and create a new layer
WORKDIR : Set working directory (similar to cd)
ADD / COPY : Add files/directories to the image (COPY is preferred; ADD can also extract archives)
ENV : Define environment variables
EXPOSE : Document the ports the container listens on
CMD : Default command when the container starts (overridden by docker run)
ENTRYPOINT : Command that always runs; often combined with a wrapper script for flexibility
5. Publishing Images to Registries
5.1 Docker Hub (Public)
Docker Hub works like GitHub for container images.
https://hub.docker.com/
# Log in to Docker Hub
docker login
# Tag the image with your Docker Hub username
docker tag myimage username/myimage
# Push the image
docker push username/myimage
# Pull the image to verify
docker pull username/myimage5.2 Private Registry
For confidential images, run a private Docker registry.
https://yeasy.gitbooks.io/docker_practice/repository/registry.html
# Pull the official registry image
docker pull registry
# Run the registry container with port and volume mapping
docker run -d -p 5000:5000 -v /opt/data/registry:/var/lib/registry registry
# Configure Docker daemon to allow insecure HTTP registry
cat > /etc/docker/daemon.json <<EOF
{
"insecure-registries": ["192.168.11.37:5000"]
}
EOF
systemctl daemon-reload
systemctl restart docker
# Tag and push an image to the private registry
docker tag myimage 192.168.11.37:5000/myimage
docker push 192.168.11.37:5000/myimage
# Pull from the private registry
docker pull 192.168.11.37:5000/myimage6. Hands‑On Example: Flask Application in a Docker Container
Create app.py:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "hello docker"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080)Create Dockerfile:
FROM python:2.7
LABEL maintainer="温而新"
RUN pip install flask
COPY app.py /app/
WORKDIR /app
EXPOSE 8080
CMD ["python", "app.py"]Build, run, and push the image:
# Build the image
docker build -t peng104/flask-hello-docker .
# List images
docker image ls
# Run the container with port mapping
docker run -d -p 8080:8080 peng104/flask-hello-docker
# Verify the container is running
docker container ls
# Tag and push to private registry
docker tag peng104/flask-hello-docker 192.168.11.37:5000/peng-flaskweb
docker push 192.168.11.37:5000/peng-flaskwebSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
