Canonical: https://vpsmap.net/en/guides/docker/
Language: en
Updated: 2026-09-26T00:00:00+08:00

Application Deployment

# Production Docker and Compose Architecture in Practice: Container Orchestration, Storage, and Security on Overseas Optimized VPS Hosting

VPSMap Editorial · Updated 2026-09-26 · 32 min read · [Plain-text version](https://vpsmap.net/guides/docker/index.md)

For overseas and cross-border workloads, containerized architectures on high-performance cloud servers with optimized routes such as CN2 GIA, CMIN2, and AS9929, including BandwagonHost and DMIT, have become standard practice for modern web services. These VPS plans often provide very low network jitter and high-throughput NVMe storage, but on typical lightweight production nodes, usually 1~~4 vCPU CPU、1~~4GB memory and 20~80GB storage), copying local-development defaults when deploying Docker can cause cascading system failures: uncontrolled container logs fill the system disk, Docker silently changes iptables rules and exposes unauthorized ports publicly, and missing resource limits trigger kernel OOM (Out Of Memory), making the instance unreachable.

This article systematically covers the complete process of building a robust, self-healing Docker and Compose environment that meets security and compliance requirements on overseas optimized-routing VPS instances. It includes low-level host initialization, core Daemon tuning, network traffic isolation, production microservices topology orchestration, and emergency disaster recovery strategies using provider control panels.

## One. Baseline Host Tuning and Adaptation to Cloud Provider Features[#](https://vpsmap.net/en/guides/docker/#section-1)

Containers share the host's Linux kernel, so the underlying OS baseline directly determines runtime stability. Use a stable long-term-supported distribution such as Debian 12 Bookworm or Ubuntu 24.04 LTS.

### 1. Cloud Platform Initialization and Access Control Adaptation[#](https://vpsmap.net/en/guides/docker/#section-2)

Cloud providers differ significantly in initialization and authentication mechanisms. Understand their networking and terminal access characteristics before deploying the container engine:

- **DMIT Instance Characteristics**：

- When provisioned, DMIT instances usually disable direct remote root login with a password by default and require SSH key authentication.

- In the management console's `Access` the panel supports injecting or resetting SSH keys and the root password. Pay special attention to the following:**After Updating Keys or Passwords in the DMIT Panel, You Must Hard-Reboot the Instance Through the Control Panel (Reboot)**, after which the underlying metadata push and cloud-init take effect.

- If a container orchestration mistake blocks the SSH port or freezes the system, use the Web interface provided by the DMIT console: `Console`(a VNC-based emergency terminal) to bypass public-network SSH for out-of-band troubleshooting.

- **BandwagonHost Instance Characteristics**：

- In BandwagonHost's KiwiVM control panel system, the KiwiVM management password, client area billing password, and system root password are all independent.

- If container networking, the docker0 bridge, or host firewall adjustments accidentally cut off connectivity, do not reset the system immediately. Log in to KiwiVM and use its built-in `Interactive Console`(Interactive Console) provides direct access to the host Shell so you can stop malfunctioning containers or reset network routes.

### 2. Swap Space and Kernel Virtual Memory Pressure Controls[#](https://vpsmap.net/en/guides/docker/#section-3)

Running multiple container services on a small VPS with 1GB~2GB of RAM can easily cause sudden memory spikes. Without Swap configured, the kernel's OOM Killer can instantly terminate the process using the most memory, usually a database container or dockerd.

Run the following commands to create a 2GB swap file and reduce the kernel's tendency to use Swap, preserving NVMe lifespan and performance:

bash

```
# 检查现有 Swap
swapon --show

# 创建 2GB Swap 文件（若已有合理 Swap 可跳过）
fallocate -l 2G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=2048
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

# 持久化挂载
echo '/swapfile none swap sw 0 0' >> /etc/fstab

# 优化内存置换倾向（仅在物理内存剩余不足 10% 时才使用 Swap）
sysctl vm.swappiness=10
sysctl vm.vfs_cache_pressure=50
echo 'vm.swappiness=10' >> /etc/sysctl.d/99-docker-system.conf
echo 'vm.vfs_cache_pressure=50' >> /etc/sysctl.d/99-docker-system.conf
```

## Two. Deploy the Official Docker Engine and Compose Plugin[#](https://vpsmap.net/en/guides/docker/#section-4)

Do Not Use the Distribution Repository's Bundled `apt install docker.io` or the outdated standalone binary `docker-compose`(the Python-maintained version). Production environments must use Docker's official upstream repository and the tightly integrated `docker-compose-plugin`(V2 command set:`docker compose`）。

bash

```
# 1. 彻底清理可能残留的历史冲突软件包
apt-get remove -y docker docker-engine docker.io containerd runc 2>/dev/null

# 2. 安装基础通信与安全认证组件
apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    curl \
    gnupg \
    lsb-release

# 3. 规范配置官方 GPG 密钥环目录
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg

# 4. 写入稳定版仓库配置（以 Debian 系统为例）
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  tee /etc/apt/sources.list.d/docker.list > /dev/null

# 5. 安装核心引擎与 Compose V2 插件
apt-get update
apt-get install -y --no-install-recommends \
    docker-ce \
    docker-ce-cli \
    containerd.io \
    docker-buildx-plugin \
    docker-compose-plugin

# 6. 验证核心组件版本
docker --version
docker compose version
```

## Three. Production-Grade Daemon Configuration (`/etc/docker/daemon.json` essential tuning)[#](https://vpsmap.net/en/guides/docker/#section-5)

This is the highest-risk and most frequently overlooked aspect of operating a small VPS. Docker's default unlimited logging is the biggest threat to small storage volumes. Create and configure `/etc/docker/daemon.json`：

json

```
{
  "storage-driver": "overlay2",
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "20m",
    "max-file": "3"
  },
  "live-restore": true,
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 65535,
      "Soft": 65535
    }
  },
  "dns": [
    "1.1.1.1",
    "8.8.8.8"
  ],
  "default-address-pools": [
    {
      "base": "172.24.0.0/16",
      "size": 24
    }
  ]
}
```

### In-Depth Analysis of Key Production Parameters:[#](https://vpsmap.net/en/guides/docker/#section-6)

1. **Log Rotation and Truncation (`max-size: 20m` & `max-file: 3`）**: Each container's stdout/stderr logs automatically rotate at 20MB, retaining at most 3 archived copies. Total log storage per container is capped at 60MB. Without this setting, repeated Redis errors or continuous web application logging can fill a 20GB~40GB system disk in days, causing the system, due to `No space left on device` and completely reject remote login or cause database persistence failures and corruption.

1. **Graceful Update Protection (`live-restore: true`）**: When applying kernel patches or performing apt upgrades `docker-ce` or run `systemctl restart docker` when the host's dockerd daemon restarts**Will Not Kill Running Application Containers**. This allows microservices to continue serving users without interruption during maintenance on a single node.

1. **Preventing Private Subnet Conflicts (`default-address-pools`）**: Docker's default bridge allocation uses `172.17.0.0/16` starting subnet, which can easily overlap with some data center VPC routes or reserved addresses in self-managed WireGuard/Tailscale Mesh networks. Explicitly restrict the allocation pool to `172.24.0.0/16` and with `/24` subdivide the subnets to eliminate routing blackholes between them.

1. **Upstream DNS Override (`dns`）**: Some cloud server templates configure the following by default: `/etc/resolv.conf` points to the local loopback stub resolver. If upstream recursive DNS becomes unstable on the overseas network, containers may frequently experience DNS timeouts during API calls, communication with external CAPTCHA services, or data retrieval. Explicitly specifying Cloudflare and Google's Anycast public DNS can significantly improve resolution stability.

Load the Configuration and Start the Service:

bash

```
systemctl daemon-reload
systemctl restart docker
systemctl enable docker
```

## Four. Container Network Security: Avoiding the iptables Bypass Trap[#](https://vpsmap.net/en/guides/docker/#section-7)

In Linux administration, many site owners routinely use UFW or the system's built-in firewall to execute `ufw default deny incoming`. However,**Docker has a well-known security-related behavior: by default, dockerd writes directly to the underlying iptables `PREROUTING` and `FORWARD` insert into the chain `DOCKER` rules, causing exposed container ports to bypass UFW filtering completely!**

For example, declare the following in Compose:

yaml

```
ports:
  - "3306:3306"
```

Even if you have run the following on the host: `ufw deny 3306`, public network scanners can still connect directly to your database port and brute-force it.

### The Golden Rule of Production Network Security:[#](https://vpsmap.net/en/guides/docker/#section-8)

1. **Minimize Public Internet Exposure Completely**: Except for reverse proxies responsible for traffic distribution and SSL termination (such as Nginx and Caddy), which expose `80` and `443` ports, all backend components (Node.js, Go, Python, PostgreSQL, Redis)**Never Expose External Port Mappings to the Public Internet**.

1. **Force Binding to Local Loopback**: if debugging genuinely requires accessing a container port from the host, explicitly bind it to `127.0.0.1`：

yaml

```
ports:
  - "127.0.0.1:8080:8080" # 仅宿主机内部或通过 SSH 隧道可达
```

1. **Multilayer Network Segregation**: Separate at least two bridge networks in Compose:

- `public_net`: shared by reverse-proxy and application access-layer containers;

- `secure_net`: Shared by the application access layer, persistent database, and cache; the reverse proxy is not permitted on this network.

## Five. Declarative Production Microservice Orchestration: Docker Compose Best Practices[#](https://vpsmap.net/en/guides/docker/#section-9)

The following topology shows a typical production architecture: a highly reliable reverse proxy (Caddy automatically obtains and renews Let's Encrypt certificates), an application service (Node.js API), a persistent database (PostgreSQL 16), and a separate cache (Redis 7 Alpine).

### 1. Directory Structure Standards[#](https://vpsmap.net/en/guides/docker/#section-10)

In production, keep configuration, data, and orchestration files logically separate. Recommended directory structure:

text

```
/opt/production-stack/
├── .env                  # 敏感环境变量（严禁提交至公共代码库）
├── docker-compose.yml    # 编排定义
├── caddy/
│   └── Caddyfile         # 边缘反向代理配置
└── backups/              # 本地冷备份输出目录
```

### 2. Environment Variable Definitions (`/opt/production-stack/.env`）[#](https://vpsmap.net/en/guides/docker/#section-11)

bash

```
# 系统环境参数
COMPOSE_PROJECT_NAME=core_prod
DOMAIN_NAME=api.yourdomain.com

# 数据库机密参数
DB_USER=prod_pguser
DB_PASSWORD=Super_Secret_Postgres_Password_2026
DB_NAME=core_db

# 缓存机密参数
REDIS_PASSWORD=Strong_Redis_Auth_Token_9981
```

### 3. Production Orchestration Configuration (`/opt/production-stack/docker-compose.yml`）[#](https://vpsmap.net/en/guides/docker/#section-12)

yaml

```
services:
  # ----------------------------------------------------
  # 1. 边缘反向代理与 TLS 终结（仅此服务监听公网端口）
  # ----------------------------------------------------
  proxy:
    image: caddy:2.8-alpine
    container_name: prod_proxy
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
      - "443:443/udp" # HTTP/3 支持
    volumes:
      - ./caddy/Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
      - caddy_config:/config
    networks:
      - public_net
    deploy:
      resources:
        limits:
          memory: 128M

  # ----------------------------------------------------
  # 2. 核心业务应用层（桥接双网络）
  # ----------------------------------------------------
  app:
    image: node:20-alpine
    container_name: prod_app
    restart: unless-stopped
    working_dir: /usr/src/app
    command: sh -c "node server.js"
    environment:
      NODE_ENV: production
      DATABASE_URL: postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      REDIS_URL: redis://:${REDIS_PASSWORD}@cache:6379/0
    networks:
      - public_net
      - secure_net
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_healthy
    deploy:
      resources:
        limits:
          cpus: '1.5'
          memory: 512M

  # ----------------------------------------------------
  # 3. 持久化数据层（严格隔离于内部安全网）
  # ----------------------------------------------------
  db:
    image: postgres:16-alpine
    container_name: prod_postgres
    restart: unless-stopped
    environment:
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: ${DB_NAME}
    volumes:
      - pg_data:/var/lib/postgresql/data
    networks:
      - secure_net
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${DB_USER} -d ${DB_NAME}"]
      interval: 10s
      timeout: 5s
      retries: 5
    deploy:
      resources:
        limits:
          memory: 768M

  # ----------------------------------------------------
  # 4. 高速缓存层（密码保护与无公网暴露）
  # ----------------------------------------------------
  cache:
    image: redis:7-alpine
    container_name: prod_redis
    restart: unless-stopped
    command: >
      redis-server
      --requirepass ${REDIS_PASSWORD}
      --maxmemory 128mb
      --maxmemory-policy allkeys-lru
    volumes:
      - redis_data:/data
    networks:
      - secure_net
    healthcheck:
      test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]
      interval: 10s
      timeout: 5s
      retries: 3
    deploy:
      resources:
        limits:
          memory: 192M

# ----------------------------------------------------
# 存储卷定义（与宿主机文件系统物理隔离）
# ----------------------------------------------------
volumes:
  caddy_data:
  caddy_config:
  pg_data:
  redis_data:

# ----------------------------------------------------
# 内部网络隔离方案
# ----------------------------------------------------
networks:
  public_net:
    driver: bridge
  secure_net:
    driver: bridge
    internal: true # 强化标志：禁止该网段内容器直接出站访问外网，断绝数据外泄途径
```

### Key Design Points Explained:[#](https://vpsmap.net/en/guides/docker/#section-13)

- **`internal: true` Maximum Network Security**: in `secure_net` declare on `internal: true`, Docker will not create a default outbound SNAT gateway for this bridge. The PostgreSQL and Redis containers are logically disconnected from external networking and can respond only to `app` the container's local-network requests, eliminating the possibility of malicious dependencies opening reverse Shells from the internal network or leaking data.

- **Health Checks and Startup-Order Awareness (`service_healthy`）**: in a microservices architecture, use only `depends_on: [db]` only ensures that the database container has been created; it does not guarantee that initialization is complete and the database is listening. Combine it with `healthcheck` and `condition: service_healthy`, ensuring `app` the database connection pool is guaranteed to be available at startup, preventing initialization crash loops.

## Six. Automated Lifecycle Cleanup and Storage Maintenance[#](https://vpsmap.net/en/guides/docker/#section-14)

Long-running Docker hosts can easily accumulate obsolete BuildKit cache, Dangling images, and unattached anonymous volumes.

### 1. Standard Cleanup Commands[#](https://vpsmap.net/en/guides/docker/#section-15)

bash

```
# 安全清理所有无标签的“悬挂”虚悬镜像（不影响运行中服务）
docker image prune -f

# 清除超过 7 天未被任何容器引用的旧构建缓存
docker builder prune -a --filter "until=168h" -f

# 检查当前 Docker 对物理磁盘的真实占用情况
docker system df
```

### 2. Deploy an Automated Cleanup Cron Job[#](https://vpsmap.net/en/guides/docker/#section-16)

Create `/etc/cron.weekly/docker-maintenance` and grant execute permission:

bash

```
cat << 'EOF' > /etc/cron.weekly/docker-maintenance
#!/bin/sh
# 每周自动回收超过 14 天未使用的无用镜像与构建缓存，保持系统盘平稳
docker system prune -a --volumes=false --filter "until=336h" -f > /var/log/docker-prune.log 2>&1
EOF

chmod +x /etc/cron.weekly/docker-maintenance
```

## Seven. Operations Troubleshooting, Disaster Recovery Coordination, and Provider Lifecycle Policies[#](https://vpsmap.net/en/guides/docker/#section-17)

Highly available container architecture requires more than code-level orchestration; it must work seamlessly with the cloud provider's infrastructure lifecycle and operations tools.

### 1. Out-of-Band Troubleshooting and Emergency Console Recovery[#](https://vpsmap.net/en/guides/docker/#section-18)

If Docker memory exhaustion, configuration mistakes, or network conflicts completely cut off SSH, the provider's control panel is the last recovery method:

- **BandwagonHost KiwiVM Emergency Recovery Path**：

- Log in to KiwiVM and find the following in the sidebar: `Interactive Console`. This console emulates a physical keyboard and display, so you can still log in normally even if the network interface (eth0) fails or iptables rules are corrupted.

- Run in the Console `systemctl stop docker` release system memory and network locks, then use `docker stats` or `journalctl -u docker -n 100` Analyze the Cause of the Crash.

- **Snapshot and Data Center Migration Restrictions**: KiwiVM supports full-system disk snapshots. Always take one before a major Compose architecture refactor. In addition, if the server's IP is blocked by an external network (blacklisted), KiwiVM's unrestricted multi-data-center migration is limited. Strictly control network activity inside containers to prevent abuse.

- **Emergency Access and Console Procedures for DMIT Instances**：

- If you cannot connect because a container changed the SSH port or a public key was lost, open the DMIT instance control panel and select `Access` tab to reset the root password or redeploy the public key.**Remember: After Saving Changes in the DMIT Panel, Click Hard Reboot in the Console for Them to Take Effect**.

- If the instance loses all network access, click the control panel's top-right `Console`, open the Web VNC window and enter the credentials directly to log in for maintenance.

### 2. Network Billing and Traffic Usage Precautions[#](https://vpsmap.net/en/guides/docker/#section-19)

For hosts such as BandwagonHost and DMIT with premium direct international backbone connectivity, traffic allowances are a core asset:

- **Account for Traffic Used by Image Pulls**: Large development images, such as untrimmed `node:latest`, applications containing CUDA, or large Python environments) can consume 1GB~3GB of traffic in a single pull. Frequently pulling external images in CI/CD can quickly erode a VPS's monthly traffic quota.

- **Provider Rules and Refund Limits During Testing**：

- **DMIT Rules**: newly purchased instances generally within 3 days and with network usage**No More Than 30GB** to qualify for a full refund; within 30 days, partial refunds are calculated from the remaining value after applicable deductions, subject to the Terms of Service and no violations. When evaluating Docker performance or benchmarking a newly provisioned instance, avoid pulling huge images concurrently in a short period, which could immediately exceed the 30GB threshold and eliminate refund eligibility. Also note that DMIT monthly renewal invoices are generated 7 days before expiration. If an instance is suspended for nonpayment, its data is usually retained for only about 3 days before automatic permanent deletion.

- **BandwagonHost Rules**: BandwagonHost does not automatically charge credit cards or PayPal. After the invoice is generated 7 days before expiration, pay it manually or ensure sufficient account credit. Under its terms of service, one requirement for requesting a refund within 30 days of a new purchase is**Monthly Traffic Usage Must Be Below 10% of the Allowance**. If you download large numbers of Docker images or run network stress tests, monitor the control panel's Bandwidth dashboard to avoid exceeding the refund usage limit.

### 3. Persistent Data Hot-Dump (Cold Backup) Script[#](https://vpsmap.net/en/guides/docker/#section-20)

Cloud server data can be irreversibly deleted after nonpayment-related shutdowns or severe hardware failures, so data stored in Docker volumes must be backed up regularly offline or off-site.

Create a Routine Hot-Dump Script on the Host `/opt/production-stack/backup.sh`：

bash

```
#!/bin/bash
set -eo pipefail

BACKUP_DIR="/opt/production-stack/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
PROJECT="core_prod"

mkdir -p "${BACKUP_DIR}"

echo "[*] 开始导出 PostgreSQL 数据库转储..."
docker compose -f /opt/production-stack/docker-compose.yml exec -T db \
    pg_dump -U prod_pguser -d core_db | gzip > "${BACKUP_DIR}/db_${TIMESTAMP}.sql.gz"

echo "[*] 开始备份持久化应用数据卷..."
# 利用临时容器打包命名数据卷
docker run --rm \
    -v core_prod_caddy_data:/volume_data:ro \
    -v "${BACKUP_DIR}":/backup \
    alpine tar czf "/backup/caddy_data_${TIMESTAMP}.tar.gz" -C /volume_data .

# 自动清理 14 天前的历史冷备份文件
find "${BACKUP_DIR}" -type f -name "*.tar.gz" -mtime +14 -delete
find "${BACKUP_DIR}" -type f -name "*.sql.gz" -mtime +14 -delete

echo "[✓] 备份完成：${TIMESTAMP}"
```

combined with `crontab -e` Schedule silent execution every day at 3 a.m.:

cron

```
0 3 * * * /bin/bash /opt/production-stack/backup.sh > /dev/null 2>&1
```

## Eight. Core Configuration Validation Checklist[#](https://vpsmap.net/en/guides/docker/#section-21)

Before moving production services to a container cluster, verify each of the following items:

| Validation Criteria | Verification Command / Action | Expected Standard Output / Behavior |
| --- | --- | --- |
| **Storage Driver** | `docker info \| grep 'Storage Driver'` | must be `overlay2` |
| **Log Truncation** | `docker inspect <容器ID> \| grep -A 5 "LogConfig"` | the driver to `json-file`, including `max-size` and `max-file` Restrictions |
| **Seamless Live Updates** | `docker info \| grep 'Live Restore Enabled'` | is shown as `true` |
| **Port Compliance** | `netstat -tlpn \| grep -E 'docker\|dockerd'` | The Host Exposes Only `80`、`443` or `127.0.0.1` Loopback Interface, with No Direct Public Access to the Database |
| **Memory Cap** | `docker stats --no-stream` | All application containers show explicit `MEM USAGE / LIMIT` thresholds, with no unlimited containers |
| **Emergency Access** | Test Authentication in the Provider's Console in Advance | Know How to Log In Through Web Console / Interactive Console So You Retain Control Without SSH |

These comprehensive baseline optimizations, tighter network exposure, and orchestration practices harness the strong single-core performance and high-speed networking of overseas optimized-routing VPS instances while fundamentally avoiding resource leaks, exposed ports, and system outages, delivering robust production-grade container hosting.
