- Understanding Docker Technology
- Docker vs Virtual Machines
- Basic Commands
- Docker Data Volumes
- Docker Networking
- Building Custom Images
- Docker Compose
- Practical Examples
- Best Practices
- FAQ
- Summary
- References
Understanding Docker Technology
Docker is a platform designed to help developers build, share, and run container applications. It handles the tedious setup, so you can focus on the code. Docker is an open-source application container engine, built on the Go programming language and released under the Apache 2.0 license. Docker allows developers to package their applications and dependent packages into a lightweight, portable container, which can then be deployed on any popular Linux machine, and also enables virtualization.
Containers utilize a sandbox mechanism exclusively, with no interfaces between them (similar to apps on an iPhone). More importantly, the performance overhead of containers is extremely low.
Application Scenarios of Docker
| Scenario | Description |
|---|---|
| Microservices architecture | Each service is containerized independently, facilitating management and scalability |
| CI/CD pipeline | Integrate with Jenkins/GitLab CI to achieve automated build and testing |
| Development environment standardization | New members can start a full set of dependent services (such as databases and message queues) with one click |
| Cloud-native foundation | Orchestration tools such as Kubernetes manage container clusters based on Docker |
Core Advantages
| Advantage | Description |
|---|---|
| Cross-platform consistency | Address the issue of “it works on my machine” and ensure consistency across development, testing, and production environments |
| Resource efficiency | Containers directly share the host kernel, eliminating the need to virtualize the entire operating system, thereby saving memory and CPU resources |
| Rapid deployment | Launch containers in seconds and support automated scaling |
| Isolation | Each container possesses an independent file system, network, and process space |
Core Concepts
| Concept | Description |
|---|---|
| Container | A lightweight running instance that contains application code, runtime environment, and dependent libraries. It is created based on an image, isolated from other containers, and shares the host operating system kernel (more efficient than virtual machines) |
| Image | A read-only template that defines the runtime environment of a container (such as operating system, software configuration, etc.). It optimizes space and build speed through layered storage |
| Dockerfile | A text file that describes how to automatically build an image (such as specifying the base image, installing software, copying files, etc.) |
| Repository/Registry | A platform for storing and distributing images, such as Docker Hub (the official public registry) or private registries (like Harbor) |
Docker vs Virtual Machines
| Feature | Virtual Machine | Docker Container |
|---|---|---|
| Isolation Level | Hardware-level virtualization | Operating system-level virtualization |
| Operating System | Each VM requires a complete OS | Sharing the host OS kernel |
| Resource Consumption | Heavyweight, consuming more resources | Lightweight, consuming less resources |
| Startup Time | Minutes | Seconds |
| Performance Overhead | Relatively high | Close to native performance |
| Image Size | GB level | MB level |
Architecture Comparison:
1 | Traditional VMs: Docker Containers: |
Basic Commands
Image Commands
1 | # Pull an image (such as the official Nginx image) |
Container Commands
1 | # Run a container (-d for detached, -p for port mapping) |
System Commands
1 | # View Docker system usage |
Docker Data Volumes
What is a Data Volume
Data Volume is a virtual directory that acts as a bridge between container directories and host directories. It solves several problems:
| Problem | Solution |
|---|---|
| Data persistence | Data remains when container is removed |
| Configuration management | Easy to modify configuration files |
| Static resources | Serve external static files |
Volume Commands
1 | # Create a volume |
Mounting Local Directories
1 | # Mount local directory (use absolute path or ./) |
Important: Local directories must start with / or ./. Names without these prefixes are treated as volume names.
Docker Networking
Default Networks
| Network | Description |
|---|---|
bridge |
Default network for containers; provides isolation |
host |
Shares host network stack; no isolation |
none |
No network connectivity |
Custom Networks
1 | # Create a custom network |
Key Benefit: In custom networks, containers can communicate using container names as hostnames:
1 | # In 'my-network', 'mysql' container can be accessed via 'mysql' hostname |
Building Custom Images
Image Structure
Docker images are built in layers:
1 | Layer 4: Application Layer (your jar/code) |
Dockerfile Syntax
Common Dockerfile instructions:
| Instruction | Description | Example |
|---|---|---|
FROM |
Base image | FROM openjdk:11-jre |
ENV |
Environment variables | ENV TZ=Asia/Shanghai |
COPY |
Copy files from host | COPY app.jar /app.jar |
ADD |
Copy and extract archives | ADD config.tar.gz /config |
RUN |
Execute commands | RUN apt-get update |
EXPOSE |
Expose ports | EXPOSE 8080 |
ENTRYPOINT |
Container startup command | ENTRYPOINT ["java", "-jar", "/app.jar"] |
CMD |
Default command arguments | CMD ["--server.port=8080"] |
Building Images
1 | # Build from Dockerfile in current directory |
Docker Compose
Docker Compose allows you to define and run multi-container applications using a YAML file.
Basic Syntax
1 | version: "3.8" |
Common Commands
1 | # Start all services |
Practical Examples
Deploying MySQL
1 | docker run -d \ |
Deploying a Java Application
Dockerfile:
1 | FROM openjdk:11-jre-slim |
Build and Run:
1 | # Build image |
Best Practices
Security
- Use specific image versions: Avoid
latesttag in production; use explicit version numbers - Run as non-root user: Add
USERinstruction in Dockerfile1
2RUN adduser -D appuser
USER appuser - Scan images for vulnerabilities: Use
docker scanor integrate with CI/CD - Don’t embed secrets: Use environment variables, Docker secrets, or external vaults
Performance
Leverage build cache: Order Dockerfile instructions from least to most frequently changing
Minimize layers: Combine multiple
RUNcommands when logicalUse multi-stage builds:
1
2
3
4
5
6
7
8
9# Build stage
FROM maven:3.8-openjdk-11 AS build
COPY . .
RUN mvn clean package
# Runtime stage
FROM openjdk:11-jre-slim
COPY --from=build /app/target/*.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
Maintenance
- Label your images:
1
2
3LABEL maintainer="your-email@example.com"
LABEL version="1.0"
LABEL description="My Application" - Use
.dockerignore: Exclude unnecessary files from build context - Set resource limits: Prevent containers from consuming all resources
- Implement health checks:
1
2HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1
Production Readiness
| Practice | Command/Config |
|---|---|
| Restart policy | docker run --restart unless-stopped |
| Resource limits | docker run --memory=512m --cpus=1.0 |
| Log rotation | Configure Docker daemon logging options |
| Network isolation | Use custom networks, not default bridge |
FAQ
Q: What is the difference between COPY and ADD in Dockerfile?
A: COPY simply copies files from host to container. ADD has additional features:
- Can extract local tar archives automatically
- Can download files from URLs
Recommendation: Use COPY for most cases; use ADD only when you need its special features.
Q: How do I access a container from another machine on the same network?
A: Use the host machine’s IP address with the mapped port. For example, if the host IP is 192.168.1.100 and you mapped port 8080:
1 | http://192.168.1.100:8080 |
Q: Why is my container exiting immediately?
A: Common causes:
- The foreground process exited (containers stop when the main process stops)
- Incorrect command or entrypoint
- Application error on startup
Debug: Check logs with docker logs <container> or run interactively without -d flag.
Q: How do I persist data when a container is removed?
A: Use named volumes or bind mounts:
1 | # Named volume |
Q: What is the difference between docker-compose and docker compose?
A: docker-compose (V1) is the Python-based legacy tool. docker compose (V2) is the Go-based plugin integrated into Docker CLI. V2 is now recommended.
Q: How do I reduce Docker image size?
A: Strategies:
- Use smaller base images (Alpine, Distroless)
- Use multi-stage builds
- Remove unnecessary dependencies and cache files
- Minimize layer count where appropriate
Q: Can I run GUI applications in Docker?
A: Yes, but it’s complex. You need to:
- Share X11 socket with the host
- Set appropriate DISPLAY environment variable
- Handle permissions
Generally not recommended for production, but possible for development.
Q: How do I troubleshoot network connectivity between containers?
A: Steps:
- Ensure containers are on the same network
- Verify using container names for DNS resolution
- Use
docker network inspectto check configuration - Use
docker execto ping from inside containers
Summary
Docker revolutionizes application deployment through containerization. Key takeaways:
| Concept | Key Point |
|---|---|
| Containers vs VMs | Containers share host kernel; VMs virtualize hardware |
| Images vs Containers | Images are blueprints; containers are running instances |
| Data Persistence | Use volumes for data that must survive container restarts |
| Networking | Custom networks enable service discovery via container names |
| Docker Compose | Ideal for multi-container application orchestration |
Docker enables developers to build once and run anywhere, solving the “it works on my machine” problem and streamlining the path from development to production.