大海's Blog

Docker + Caddy 部署 WordPress 实战

全文约 7,641 字预计阅读 20 分钟

这篇文章按我当前的搬瓦工 VPS 部署整理:Caddy 运行在宿主机,Nginx、PHP-FPM、MariaDB 与 Redis 运行在 Docker 容器中。

它不是「Caddy 容器 + WordPress 官方 Apache 镜像」的简化版;文中的目录、镜像、端口与配置都和下载包中的安装脚本一致。

#一、实际访问链路

 1访客
 2  ↓
 3Cloudflare
 4  ↓ HTTPS
 5搬瓦工 VPS 宿主机 Caddy :443
 6  ↓ 反向代理到宿主机回环地址
 7127.0.0.1:8080(Docker Nginx 容器)
 8  ↓ FastCGI
 9PHP-FPM :9000(Docker PHP 容器)
10  ↓
11MariaDB / Redis(仅 Docker 内部网络)

这套结构有几个明确边界:

  • 只有宿主机 Caddy 对公网开放 80/443。
  • Nginx 只监听宿主机 127.0.0.1:8080。
  • PHP-FPM、MariaDB 和 Redis 不向宿主机或公网映射端口。
  • WordPress 文件直接放在 /opt/docker/blog/www/,不会出现额外的 WordPress 目录层级。

#二、完整目录结构

 1/opt/docker/blog/
 2├── .env                         # 数据库密码、WordPress 密钥和部署参数
 3├── .bwg-wordpress-oneclick      # 安装实例标记
 4├── docker-compose.yml           # 四个容器及网络、资源限制、健康检查
 5├── Dockerfile                   # 自定义 PHP-FPM 镜像
 6├── nginx/
 7│   ├── nginx.conf               # Nginx 主配置
 8│   ├── default.conf             # WordPress 站点、FastCGI、真实 IP、安全规则
 9│   └── logs/                    # Nginx 日志
10├── php/
11│   ├── conf.d/
12│   │   └── 99-blog.ini          # PHP 与 OPcache 配置
13│   └── php-fpm.d/
14│       └── zz-blog.ini          # PHP-FPM 进程配置
15└── www/                         # WordPress 根目录
16    ├── index.php
17    ├── wp-config.php
18    ├── wp-admin/
19    ├── wp-content/
20    └── wp-includes/

php/php-fpm.d/zz-blog.ini 在 Compose 中挂载为容器内的 zz-blog.conf,这样 PHP-FPM 才会按 .conf 后缀加载它。

#三、关键配置文件全文

#1. .env.example

真实 .env 不公开。安装脚本会把占位符替换为域名、端口、项目名和随机生成的密码。

DOMAIN=__DOMAIN__
PUBLIC_HTTPS_ORIGIN=__PUBLIC_HTTPS_ORIGIN__
COMPOSE_PROJECT_NAME=__COMPOSE_PROJECT_NAME__
BLOG_PORT=__BLOG_PORT__
HTTP_PORT=__HTTP_PORT__
HTTPS_PORT=__HTTPS_PORT__
BLOG_SUBNET=__BLOG_SUBNET__
BLOG_GATEWAY=__BLOG_GATEWAY__

MARIADB_DATABASE=wordpress
MARIADB_USER=wordpress
MARIADB_PASSWORD=__MARIADB_PASSWORD__
MARIADB_ROOT_PASSWORD=__MARIADB_ROOT_PASSWORD__

WORDPRESS_AUTH_KEY=__WORDPRESS_AUTH_KEY__
WORDPRESS_SECURE_AUTH_KEY=__WORDPRESS_SECURE_AUTH_KEY__
WORDPRESS_LOGGED_IN_KEY=__WORDPRESS_LOGGED_IN_KEY__
WORDPRESS_NONCE_KEY=__WORDPRESS_NONCE_KEY__
WORDPRESS_AUTH_SALT=__WORDPRESS_AUTH_SALT__
WORDPRESS_SECURE_AUTH_SALT=__WORDPRESS_SECURE_AUTH_SALT__
WORDPRESS_LOGGED_IN_SALT=__WORDPRESS_LOGGED_IN_SALT__
WORDPRESS_NONCE_SALT=__WORDPRESS_NONCE_SALT__

#2. docker-compose.yml

四个容器共享 blog 网络。Nginx 只映射回环端口,MariaDB 和 Redis 不映射宿主机端口。

  1services:
  2  nginx:
  3    image: ${NGINX_IMAGE:-nginx:stable-alpine}
  4    container_name: ${COMPOSE_PROJECT_NAME:-blog}-nginx
  5    restart: unless-stopped
  6    ports:
  7      - "127.0.0.1:${BLOG_PORT:-8080}:80"
  8    volumes:
  9      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
 10      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
 11      - ./nginx/logs:/var/log/nginx
 12      - ./www:/var/www/html
 13    depends_on:
 14      php:
 15        condition: service_healthy
 16    networks:
 17      - blog
 18    security_opt:
 19      - no-new-privileges:true
 20    pids_limit: 100
 21    mem_limit: 64m
 22    healthcheck:
 23      test: ["CMD", "nginx", "-t"]
 24      interval: 30s
 25      timeout: 5s
 26      retries: 3
 27      start_period: 10s
 28    environment:
 29      TZ: Asia/Shanghai
 30
 31  php:
 32    build:
 33      context: .
 34      dockerfile: Dockerfile
 35      args:
 36        PHP_BASE_IMAGE: ${PHP_BASE_IMAGE:-php:8.5-fpm}
 37    image: ${COMPOSE_PROJECT_NAME:-blog}-php:8.5
 38    container_name: ${COMPOSE_PROJECT_NAME:-blog}-php
 39    restart: unless-stopped
 40    working_dir: /var/www/html
 41    environment:
 42      TZ: Asia/Shanghai
 43      DOMAIN: ${DOMAIN:?Set DOMAIN}
 44      PUBLIC_HTTPS_ORIGIN: ${PUBLIC_HTTPS_ORIGIN:?Set PUBLIC_HTTPS_ORIGIN}
 45      WORDPRESS_DB_HOST: db:3306
 46      WORDPRESS_DB_NAME: ${MARIADB_DATABASE:?Set MARIADB_DATABASE}
 47      WORDPRESS_DB_USER: ${MARIADB_USER:?Set MARIADB_USER}
 48      WORDPRESS_DB_PASSWORD: ${MARIADB_PASSWORD:?Set MARIADB_PASSWORD}
 49      WORDPRESS_AUTH_KEY: ${WORDPRESS_AUTH_KEY:?Set WORDPRESS_AUTH_KEY}
 50      WORDPRESS_SECURE_AUTH_KEY: ${WORDPRESS_SECURE_AUTH_KEY:?Set WORDPRESS_SECURE_AUTH_KEY}
 51      WORDPRESS_LOGGED_IN_KEY: ${WORDPRESS_LOGGED_IN_KEY:?Set WORDPRESS_LOGGED_IN_KEY}
 52      WORDPRESS_NONCE_KEY: ${WORDPRESS_NONCE_KEY:?Set WORDPRESS_NONCE_KEY}
 53      WORDPRESS_AUTH_SALT: ${WORDPRESS_AUTH_SALT:?Set WORDPRESS_AUTH_SALT}
 54      WORDPRESS_SECURE_AUTH_SALT: ${WORDPRESS_SECURE_AUTH_SALT:?Set WORDPRESS_SECURE_AUTH_SALT}
 55      WORDPRESS_LOGGED_IN_SALT: ${WORDPRESS_LOGGED_IN_SALT:?Set WORDPRESS_LOGGED_IN_SALT}
 56      WORDPRESS_NONCE_SALT: ${WORDPRESS_NONCE_SALT:?Set WORDPRESS_NONCE_SALT}
 57    volumes:
 58      - ./www:/var/www/html
 59      - ./php/conf.d/99-blog.ini:/usr/local/etc/php/conf.d/99-blog.ini:ro
 60      - ./php/php-fpm.d/zz-blog.ini:/usr/local/etc/php-fpm.d/zz-blog.conf:ro
 61    depends_on:
 62      db:
 63        condition: service_healthy
 64      redis:
 65        condition: service_healthy
 66    networks:
 67      - blog
 68    security_opt:
 69      - no-new-privileges:true
 70    pids_limit: 100
 71    mem_limit: 512m
 72    healthcheck:
 73      test: ["CMD", "php-fpm", "-t"]
 74      interval: 30s
 75      timeout: 5s
 76      retries: 3
 77      start_period: 15s
 78
 79  db:
 80    image: ${MARIADB_IMAGE:-mariadb:11.4}
 81    container_name: ${COMPOSE_PROJECT_NAME:-blog}-db
 82    restart: unless-stopped
 83    environment:
 84      TZ: Asia/Shanghai
 85      MARIADB_DATABASE: ${MARIADB_DATABASE:?Set MARIADB_DATABASE}
 86      MARIADB_USER: ${MARIADB_USER:?Set MARIADB_USER}
 87      MARIADB_PASSWORD: ${MARIADB_PASSWORD:?Set MARIADB_PASSWORD}
 88      MARIADB_ROOT_PASSWORD: ${MARIADB_ROOT_PASSWORD:?Set MARIADB_ROOT_PASSWORD}
 89    volumes:
 90      - db-data:/var/lib/mysql
 91    command:
 92      - --character-set-server=utf8mb4
 93      - --collation-server=utf8mb4_unicode_ci
 94      - --innodb-buffer-pool-size=256M
 95      - --max-connections=30
 96    networks:
 97      - blog
 98    security_opt:
 99      - no-new-privileges:true
100    pids_limit: 200
101    mem_limit: 640m
102    healthcheck:
103      test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
104      interval: 10s
105      timeout: 5s
106      retries: 10
107      start_period: 30s
108
109  redis:
110    image: ${REDIS_IMAGE:-redis:7.4-alpine}
111    container_name: ${COMPOSE_PROJECT_NAME:-blog}-redis
112    restart: unless-stopped
113    command:
114      - redis-server
115      - --save
116      - ""
117      - --appendonly
118      - "no"
119      - --maxmemory
120      - 64mb
121      - --maxmemory-policy
122      - allkeys-lru
123    networks:
124      - blog
125    security_opt:
126      - no-new-privileges:true
127    pids_limit: 50
128    mem_limit: 96m
129    healthcheck:
130      test: ["CMD", "redis-cli", "ping"]
131      interval: 10s
132      timeout: 3s
133      retries: 5
134
135networks:
136  blog:
137    driver: bridge
138    ipam:
139      config:
140        - subnet: ${BLOG_SUBNET:-172.19.0.0/24}
141          gateway: ${BLOG_GATEWAY:-172.19.0.1}
142
143volumes:
144  db-data:
145    name: ${COMPOSE_PROJECT_NAME:-blog}-db-data

#3. Dockerfile

PHP 镜像包含 WordPress 常用的 MySQL、GD、EXIF、ZIP、Intl、BCMath 和 Redis 扩展。

 1ARG PHP_BASE_IMAGE=php:8.5-fpm
 2FROM ${PHP_BASE_IMAGE}
 3
 4ENV TZ=Asia/Shanghai
 5
 6RUN apt-get update \
 7    && apt-get install -y --no-install-recommends \
 8        $PHPIZE_DEPS \
 9        libfreetype6-dev \
10        libjpeg62-turbo-dev \
11        libpng-dev \
12        libwebp-dev \
13        libicu-dev \
14        libzip-dev \
15        ca-certificates \
16    && docker-php-ext-configure gd \
17        --with-freetype \
18        --with-jpeg \
19        --with-webp \
20    && docker-php-ext-install -j"$(nproc)" \
21        mysqli \
22        pdo_mysql \
23        exif \
24        gd \
25        zip \
26        intl \
27        bcmath \
28    && pecl install redis \
29    && docker-php-ext-enable redis \
30    && runtime_libs="$(dpkg-query -W -f='${binary:Package}\n' \
31        'libfreetype6' \
32        'libjpeg62-turbo' \
33        'libpng16-16*' \
34        'libwebp7' \
35        'libicu[0-9]*' \
36        'libzip[0-9]*' 2>/dev/null || true)" \
37    && if [ -n "$runtime_libs" ]; then apt-mark manual $runtime_libs; fi \
38    && apt-get purge -y --auto-remove \
39        $PHPIZE_DEPS \
40        libfreetype6-dev \
41        libjpeg62-turbo-dev \
42        libpng-dev \
43        libwebp-dev \
44        libicu-dev \
45        libzip-dev \
46    && rm -rf /var/lib/apt/lists/* /tmp/pear
47
48WORKDIR /var/www/html
49
50EXPOSE 9000
51
52CMD ["php-fpm"]

#4. nginx/nginx.conf

 1user nginx;
 2worker_processes auto;
 3
 4error_log /var/log/nginx/error.log warn;
 5pid /var/run/nginx.pid;
 6
 7events {
 8    worker_connections 1024;
 9}
10
11http {
12    include /etc/nginx/mime.types;
13    default_type application/octet-stream;
14
15    sendfile on;
16    tcp_nopush on;
17    tcp_nodelay on;
18
19    keepalive_timeout 65;
20    types_hash_max_size 2048;
21    server_tokens off;
22    access_log off;
23
24    gzip on;
25    gzip_vary on;
26    gzip_proxied any;
27    gzip_comp_level 5;
28    gzip_min_length 1024;
29    gzip_types
30        text/plain
31        text/css
32        text/xml
33        application/json
34        application/javascript
35        application/xml
36        application/rss+xml
37        image/svg+xml;
38
39    include /etc/nginx/conf.d/*.conf;
40}

#5. nginx/default.conf

这个文件负责 WordPress 固定链接、PHP-FPM、真实访客 IP、静态缓存和敏感文件保护。

 1log_format blog_json escape=json
 2    '{'
 3        '"time":"$time_iso8601",'
 4        '"timestamp":"$msec",'
 5        '"request_id":"$request_id",'
 6        '"remote_addr":"$remote_addr",'
 7        '"realip_remote_addr":"$realip_remote_addr",'
 8        '"caddy_client_ip":"$http_x_real_ip",'
 9        '"x_forwarded_for":"$http_x_forwarded_for",'
10        '"host":"$host",'
11        '"method":"$request_method",'
12        '"uri":"$uri",'
13        '"protocol":"$server_protocol",'
14        '"status":"$status",'
15        '"body_bytes_sent":"$body_bytes_sent",'
16        '"request_time":"$request_time",'
17        '"upstream_response_time":"$upstream_response_time",'
18        '"upstream_addr":"$upstream_addr",'
19        '"referer":"$http_referer",'
20        '"user_agent":"$http_user_agent"'
21    '}';
22
23server {
24    listen 80;
25    server_name _;
26
27    root /var/www/html;
28    index index.php index.html;
29
30    charset utf-8;
31    client_max_body_size 64m;
32
33    # 只信任 Caddy 的 Docker 网关,由安装脚本替换
34    set_real_ip_from __BLOG_GATEWAY__;
35    real_ip_header X-Real-IP;
36    real_ip_recursive off;
37
38    access_log /var/log/nginx/access.json blog_json;
39    error_log /var/log/nginx/error.log warn;
40
41    location / {
42        try_files $uri $uri/ /index.php?$args;
43    }
44
45    # 禁止上传目录执行 PHP
46    location ~* ^/wp-content/uploads/.*\.php$ {
47        deny all;
48    }
49
50    # 禁止访问敏感文件
51    location ~* /(wp-config\.php|wp-config-sample\.php|readme\.html|license\.txt)$ {
52        deny all;
53    }
54
55    # 禁止访问隐藏文件
56    location ~ /\.(?!well-known).* {
57        deny all;
58    }
59
60    location ~ \.php$ {
61        try_files $uri =404;
62
63        include fastcgi_params;
64
65        fastcgi_pass php:9000;
66        fastcgi_index index.php;
67
68        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
69
70        fastcgi_param HTTP_X_FORWARDED_PROTO $http_x_forwarded_proto;
71        fastcgi_param HTTP_X_REAL_IP $http_x_real_ip;
72
73        fastcgi_connect_timeout 30s;
74        fastcgi_send_timeout 120s;
75        fastcgi_read_timeout 120s;
76    }
77
78    # 静态资源缓存
79    location ~* \.(jpg|jpeg|png|gif|ico|css|js|webp|svg|woff|woff2|ttf|eot)$ {
80        expires 30d;
81        access_log off;
82        log_not_found off;
83    }
84}

#6. php/conf.d/99-blog.ini

 1; 基础设置
 2expose_php = Off
 3display_errors = Off
 4display_startup_errors = Off
 5log_errors = On
 6error_log = /proc/self/fd/2
 7
 8; 资源限制
 9memory_limit = 128M
10max_execution_time = 120
11max_input_time = 120
12max_input_vars = 3000
13
14; 文件上传
15file_uploads = On
16upload_max_filesize = 64M
17post_max_size = 64M
18max_file_uploads = 20
19
20; 安全
21session.upload_progress.enabled = Off
22zend.exception_ignore_args = On
23
24; OPcache
25opcache.enable = 1
26opcache.enable_cli = 0
27opcache.memory_consumption = 128
28opcache.interned_strings_buffer = 16
29opcache.max_accelerated_files = 20000
30opcache.validate_timestamps = 1
31opcache.revalidate_freq = 2
32opcache.save_comments = 1
33
34; 时区
35date.timezone = Asia/Shanghai

#7. php/php-fpm.d/zz-blog.ini

 1[www]
 2
 3clear_env = no
 4
 5catch_workers_output = yes
 6decorate_workers_output = no
 7
 8security.limit_extensions = .php
 9
10; 低内存 VPS 进程管理
11pm = ondemand
12pm.max_children = 2
13pm.process_idle_timeout = 10s
14pm.max_requests = 500
15
16; 请求超时
17request_terminate_timeout = 120s
18
19; 连接队列
20listen.backlog = 128

#8. www/wp-config.php

数据库和 WordPress 密钥全部从容器环境变量读取,不直接写进公开文件。

 1<?php
 2
 3define('DB_NAME', getenv('WORDPRESS_DB_NAME'));
 4define('DB_USER', getenv('WORDPRESS_DB_USER'));
 5define('DB_PASSWORD', getenv('WORDPRESS_DB_PASSWORD'));
 6define('DB_HOST', getenv('WORDPRESS_DB_HOST'));
 7
 8define('DB_CHARSET', 'utf8mb4');
 9define('DB_COLLATE', '');
10
11define('AUTH_KEY', getenv('WORDPRESS_AUTH_KEY'));
12define('SECURE_AUTH_KEY', getenv('WORDPRESS_SECURE_AUTH_KEY'));
13define('LOGGED_IN_KEY', getenv('WORDPRESS_LOGGED_IN_KEY'));
14define('NONCE_KEY', getenv('WORDPRESS_NONCE_KEY'));
15
16define('AUTH_SALT', getenv('WORDPRESS_AUTH_SALT'));
17define('SECURE_AUTH_SALT', getenv('WORDPRESS_SECURE_AUTH_SALT'));
18define('LOGGED_IN_SALT', getenv('WORDPRESS_LOGGED_IN_SALT'));
19define('NONCE_SALT', getenv('WORDPRESS_NONCE_SALT'));
20
21$table_prefix = 'wp_';
22
23$public_origin = getenv('PUBLIC_HTTPS_ORIGIN');
24$domain = getenv('DOMAIN');
25if ($public_origin) {
26    define('WP_HOME', $public_origin);
27    define('WP_SITEURL', $public_origin);
28} elseif ($domain) {
29    define('WP_HOME', 'https://' . $domain);
30    define('WP_SITEURL', 'https://' . $domain);
31}
32
33define('WP_DEBUG', false);
34define('WP_DEBUG_LOG', false);
35define('WP_DEBUG_DISPLAY', false);
36
37define('DISALLOW_FILE_EDIT', true);
38define('FS_METHOD', 'direct');
39
40define('WP_AUTO_UPDATE_CORE', 'minor');
41
42define('WP_MEMORY_LIMIT', '128M');
43define('WP_MAX_MEMORY_LIMIT', '192M');
44
45if (
46    isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
47    $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'
48) {
49    $_SERVER['HTTPS'] = 'on';
50}
51
52if (!defined('ABSPATH')) {
53    define('ABSPATH', __DIR__ . '/');
54}
55
56require_once ABSPATH . 'wp-settings.php';

#9. 宿主机 Caddy 站点配置

下面是标准 80/443 部署使用的站点配置。它只负责当前域名,不要求覆盖现有 /etc/caddy/Caddyfile 中的其他站点。

1__DOMAIN__ {
2    reverse_proxy 127.0.0.1:__BLOG_PORT__ {
3        header_up X-Real-IP {client_ip}
4        header_up X-Forwarded-For {client_ip}
5        header_up X-Forwarded-Proto https
6    }
7}

安装脚本会在 Caddy 配置目录的 sites.d/ 中创建站点文件,并确保主 Caddyfile 导入该目录。已有主配置会保留,验证通过后才 reload。

#四、手动部署顺序

如果你不使用一键脚本,可以按以下顺序执行:

 1cd /opt/docker/blog
 2
 3# 1. 检查 Compose 模型
 4docker compose config -q
 5
 6# 2. 拉取基础镜像并构建 PHP 镜像
 7docker compose pull db redis nginx
 8docker compose build php
 9
10# 3. 启动四个容器
11docker compose up -d
12
13# 4. 检查容器和源站
14docker compose ps
15curl -I -H 'Host: dahai.me' -H 'X-Forwarded-Proto: https' http://127.0.0.1:8080/
16
17# 5. 检查并重新加载宿主机 Caddy
18caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile
19systemctl reload-or-restart caddy

不要直接对已有生产配置执行 docker compose down -v。这个命令会删除数据库和 Caddy 相关命名卷。

#五、权限、缓存与安全边界

  • .env 权限为 0600,其中密码只在首次运行时生成。
  • www/wp-config.php 权限为 0640,数据库配置不向其他宿主机用户公开。
  • 默认 PHP-FPM 使用 ondemand 和最多 2 个子进程,适合低内存 VPS。
  • OPcache 默认开启,PHP 上传上限为 64MB。
  • Nginx 禁止上传目录执行 PHP,并屏蔽 wp-config.php、隐藏文件和说明文件。
  • 固定链接使用 /%postname%/,不为旧日期链接提供兼容跳转。
  • Cloudflare SSL/TLS 建议使用 Full (strict),宿主机 Caddy 继续持有有效域名证书。
  • 数据库和上传目录需要定期备份,并复制到另一台机器,不能只留在本机。

#六、实际隔离测试

我在一台 Debian 13 隔离环境中完成验证:使用独立部署目录、独立 Caddy 配置目录、独立 Compose 项目与回环测试端口。

验证结果包括:

  • Nginx、PHP-FPM、MariaDB、Redis 四个容器均为健康状态。
  • 源站 /wp-admin/install.php 返回 200。
  • 宿主机 Caddy 配置校验通过,公网 HTTPS 最终返回 200。
  • HTTP 返回 308,完整跳转为 https://localhost:18443/wp-admin/install.php。
  • 不传域名和端口参数复跑时,仍能读取 .env 中的部署参数。
  • 复跑前后 .env、Compose、Nginx、PHP 和 wp-config 的 SHA-256 均未变化。
  • Docker 子网与 Nginx 可信网关一致,FPM 和 OPcache 均已生效。
  • www/wp-config.php 权限为 0640,复跑不会递归修改整个 www/ 的权限。
  • 验证完成后,测试容器、网络、卷和目录均已清理。

#七、一键安装脚本

下载包包含安装脚本、全部配置模板和中文说明;脚本按模板生成配置,不会另造一套目录或容器结构。

#使用方法

 1unzip bwg-wordpress-one-click.zip
 2cd bwg-wordpress
 3
 4# 校验包中的脚本和模板
 5sha256sum -c SHA256SUMS
 6
 7# 查看脚本与帮助
 8less deploy-bwg-wordpress.sh
 9bash deploy-bwg-wordpress.sh --help
10
11# 将域名替换成自己的域名后执行
12sudo bash deploy-bwg-wordpress.sh blog.example.com

默认安装目录为 /opt/docker/blog,宿主机 Nginx 回环端口为 8080,Caddy 配置目录为 /etc/caddy。

如果 Docker 网络与默认子网冲突,可以调整:

1sudo BLOG_SUBNET=172.30.0.0/24 BLOG_GATEWAY=172.30.0.1 \
2  bash deploy-bwg-wordpress.sh blog.example.com

重复执行会复用 .env 和现有配置。只校验但不启动或 reload 宿主机 Caddy 时,可以使用:

1sudo SKIP_SERVICE_ACTIONS=1 bash deploy-bwg-wordpress.sh blog.example.com

#脚本全文

  1#!/usr/bin/env bash
  2# Deploy the BandwagonHost-style WordPress stack: host Caddy + Docker Nginx/PHP/MariaDB/Redis.
  3set -Eeuo pipefail
  4IFS=$'\n\t'
  5umask 077
  6
  7VERSION='2.0.2'
  8INSTALL_DIR="${INSTALL_DIR:-/opt/docker/blog}"
  9CADDY_CONFIG_ROOT="${CADDY_CONFIG_ROOT:-/etc/caddy}"
 10REQUESTED_DOMAIN="${1:-${DOMAIN:-}}"
 11COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-blog}"
 12EXPLICIT_HTTP_PORT="${HTTP_PORT:-}"
 13EXPLICIT_HTTPS_PORT="${HTTPS_PORT:-}"
 14BLOG_PORT="${BLOG_PORT:-8080}"
 15BLOG_SUBNET="${BLOG_SUBNET:-172.19.0.0/24}"
 16BLOG_GATEWAY="${BLOG_GATEWAY:-172.19.0.1}"
 17HTTP_PORT="${HTTP_PORT:-80}"
 18HTTPS_PORT="${HTTPS_PORT:-443}"
 19SKIP_DEPENDENCIES="${SKIP_DEPENDENCIES:-0}"
 20SKIP_SERVICE_ACTIONS="${SKIP_SERVICE_ACTIONS:-0}"
 21PULL_IMAGES="${PULL_IMAGES:-1}"
 22WORDPRESS_DOWNLOAD_URL="${WORDPRESS_DOWNLOAD_URL:-https://wordpress.org/latest.tar.gz}"
 23MARKER='.bwg-wordpress-oneclick'
 24SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
 25
 26log() { printf '\033[1;34m[INFO]\033[0m %s\n' "$*"; }
 27warn() { printf '\033[1;33m[WARN]\033[0m %s\n' "$*" >&2; }
 28die() { printf '\033[1;31m[ERROR]\033[0m %s\n' "$*" >&2; exit 1; }
 29trap 'die "Failed at line $LINENO. Review the output before rerunning."' ERR
 30
 31if [[ "${1:-}" == '--help' || "${1:-}" == '-h' ]]; then
 32    cat <<'HELP'
 33Usage:
 34  sudo bash deploy-bwg-wordpress.sh blog.example.com
 35
 36Defaults:
 37  INSTALL_DIR=/opt/docker/blog
 38  CADDY_CONFIG_ROOT=/etc/caddy
 39  COMPOSE_PROJECT_NAME=blog
 40  BLOG_PORT=8080
 41  BLOG_SUBNET=172.19.0.0/24
 42  BLOG_GATEWAY=172.19.0.1
 43  HTTP_PORT=80
 44  HTTPS_PORT=443
 45
 46Optional:
 47  SKIP_DEPENDENCIES=1    Do not install system packages
 48  SKIP_SERVICE_ACTIONS=1 Validate configs but do not start/reload host Caddy
 49  PULL_IMAGES=0          Do not pull Docker images
 50
 51The script expects the templates/ directory from the same package.
 52HELP
 53    exit 0
 54fi
 55
 56[[ "$EUID" -eq 0 ]] || die 'Run as root, for example with sudo.'
 57for name in docker-compose.yml Dockerfile .env.example Caddyfile.site Caddyfile.site-custom; do
 58    [[ -f "$SCRIPT_DIR/templates/$name" ]] || die "Missing template: templates/$name"
 59done
 60if ! command -v openssl >/dev/null 2>&1 || ! command -v curl >/dev/null 2>&1 || ! command -v tar >/dev/null 2>&1; then
 61    [[ "$SKIP_DEPENDENCIES" != '1' ]] || die 'openssl, curl and tar are required.'
 62    export DEBIAN_FRONTEND=noninteractive
 63    apt-get update
 64    apt-get install -y --no-install-recommends ca-certificates openssl curl tar
 65fi
 66command -v realpath >/dev/null 2>&1 || die 'realpath (coreutils) is required.'
 67
 68validate_domain() {
 69    local domain="$1"
 70    [[ -n "$domain" ]] || die 'A domain is required.'
 71    [[ "$domain" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$ ]] || die 'Invalid domain.'
 72    [[ "$domain" != *'..'* && "$domain" != *'.-'* && "$domain" != *'-.'* ]] || die 'Invalid domain labels.'
 73    if [[ "$domain" != 'localhost' ]]; then
 74        [[ "$domain" == *.* ]] || die 'Use a fully qualified domain name.'
 75        [[ ! "$domain" =~ ^[0-9.]+$ ]] || die 'Use a domain rather than an IP address.'
 76    fi
 77}
 78validate_port() {
 79    local value="$2"
 80    [[ "$value" =~ ^[0-9]+$ ]] || die "$1 must be numeric."
 81    (( value >= 1 && value <= 65535 )) || die "$1 is outside the valid range."
 82}
 83if [[ -n "$REQUESTED_DOMAIN" ]]; then
 84    validate_domain "$REQUESTED_DOMAIN"
 85fi
 86validate_port BLOG_PORT "$BLOG_PORT"
 87validate_port HTTP_PORT "$HTTP_PORT"
 88validate_port HTTPS_PORT "$HTTPS_PORT"
 89[[ "$COMPOSE_PROJECT_NAME" =~ ^[a-z][a-z0-9-]*$ ]] || die 'Invalid Compose project name.'
 90[[ "$BLOG_SUBNET" =~ ^[0-9.]+/[0-9]+$ ]] || die 'Invalid BLOG_SUBNET.'
 91[[ "$BLOG_GATEWAY" =~ ^[0-9.]+$ ]] || die 'Invalid BLOG_GATEWAY.'
 92
 93install_docker() {
 94    [[ "$SKIP_DEPENDENCIES" != '1' ]] || die 'Docker is missing and dependency installation is disabled.'
 95    [[ -r /etc/os-release ]] || die 'Cannot detect the operating system.'
 96    # shellcheck disable=SC1091
 97    . /etc/os-release
 98    [[ "${ID:-}" == 'debian' || "${ID:-}" == 'ubuntu' ]] || die 'Automatic Docker installation supports Debian/Ubuntu.'
 99    local codename="${VERSION_CODENAME:-${UBUNTU_CODENAME:-}}"
100    [[ -n "$codename" ]] || die 'Cannot determine the distribution codename.'
101    export DEBIAN_FRONTEND=noninteractive
102    apt-get update
103    apt-get install -y --no-install-recommends ca-certificates curl gnupg openssl
104    install -m 0755 -d /etc/apt/keyrings
105    curl -fsSL "https://download.docker.com/linux/${ID}/gpg" -o /etc/apt/keyrings/docker.asc
106    chmod a+r /etc/apt/keyrings/docker.asc
107    printf 'deb [arch=%s signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/%s %s stable\n' \
108        "$(dpkg --print-architecture)" "$ID" "$codename" > /etc/apt/sources.list.d/docker.list
109    apt-get update
110    apt-get install -y --no-install-recommends \
111        docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
112}
113
114if ! command -v docker >/dev/null 2>&1 || ! docker compose version >/dev/null 2>&1; then
115    install_docker
116fi
117if ! command -v caddy >/dev/null 2>&1; then
118    [[ "$SKIP_DEPENDENCIES" != '1' ]] || die 'Caddy is missing and dependency installation is disabled.'
119    export DEBIAN_FRONTEND=noninteractive
120    apt-get update
121    apt-get install -y --no-install-recommends caddy
122fi
123if command -v systemctl >/dev/null 2>&1; then
124    systemctl enable --now docker
125fi
126docker info >/dev/null 2>&1 || die 'Docker daemon is unavailable.'
127
128INSTALL_DIR="$(realpath -m "$INSTALL_DIR")"
129CADDY_CONFIG_ROOT="$(realpath -m "$CADDY_CONFIG_ROOT")"
130case "$CADDY_CONFIG_ROOT" in
131    /|/boot|/dev|/etc|/usr|/var|/root|/home|/opt|/opt/docker|/srv|/tmp|/run|/proc|/sys)
132        die "Unsafe Caddy configuration directory: $CADDY_CONFIG_ROOT" ;;
133esac
134[[ "$INSTALL_DIR$CADDY_CONFIG_ROOT" != *' '* ]] || die 'Paths containing spaces are not supported.'
135case "$INSTALL_DIR" in
136    /|/boot|/dev|/etc|/usr|/var|/root|/home|/opt|/opt/docker|/srv|/tmp|/run|/proc|/sys)
137        die "Unsafe installation directory: $INSTALL_DIR" ;;
138esac
139[[ ! -L "$INSTALL_DIR" ]] || die 'INSTALL_DIR must not be a symbolic link.'
140if [[ -e "$INSTALL_DIR" && ! -d "$INSTALL_DIR" ]]; then
141    die 'INSTALL_DIR exists but is not a directory.'
142fi
143if [[ ! -d "$INSTALL_DIR" ]]; then
144    mkdir -p "$INSTALL_DIR"
145    chmod 0755 "$INSTALL_DIR"
146fi
147[[ "$(stat -c %u "$INSTALL_DIR")" == '0' ]] || die 'Installation directory must be owned by root.'
148cd "$INSTALL_DIR"
149shopt -s nullglob dotglob
150entries=(*)
151shopt -u nullglob dotglob
152if (( ${#entries[@]} > 0 )) && [[ ! -f "$MARKER" ]]; then
153    die 'Non-empty directory is not a recognized one-click installation.'
154fi
155if [[ ! -f "$MARKER" ]]; then
156    printf 'version=%s\nproject=%s\n' "$VERSION" "$COMPOSE_PROJECT_NAME" > "$MARKER"
157    chmod 0644 "$MARKER"
158fi
159
160if [[ ! -f .env && -z "$REQUESTED_DOMAIN" ]]; then
161    die 'A domain is required for a new installation.'
162fi
163if [[ ! -f .env ]]; then
164    log 'Creating .env with random database and WordPress secrets.'
165    PUBLIC_HTTPS_ORIGIN="https://${REQUESTED_DOMAIN}"
166    if [[ "$HTTPS_PORT" != '443' ]]; then
167        PUBLIC_HTTPS_ORIGIN="${PUBLIC_HTTPS_ORIGIN}:${HTTPS_PORT}"
168    fi
169    env_tmp="$(mktemp '.env.tmp.XXXXXX')"
170    sed \
171        -e "s|__DOMAIN__|$REQUESTED_DOMAIN|g" \
172        -e "s|__PUBLIC_HTTPS_ORIGIN__|$PUBLIC_HTTPS_ORIGIN|g" \
173        -e "s|__COMPOSE_PROJECT_NAME__|$COMPOSE_PROJECT_NAME|g" \
174        -e "s|__BLOG_PORT__|$BLOG_PORT|g" \
175        -e "s|__HTTP_PORT__|$HTTP_PORT|g" \
176        -e "s|__HTTPS_PORT__|$HTTPS_PORT|g" \
177        -e "s|__BLOG_SUBNET__|$BLOG_SUBNET|g" \
178        -e "s|__BLOG_GATEWAY__|$BLOG_GATEWAY|g" \
179        -e "s|__MARIADB_PASSWORD__|$(openssl rand -hex 32)|g" \
180        -e "s|__MARIADB_ROOT_PASSWORD__|$(openssl rand -hex 32)|g" \
181        -e "s|__WORDPRESS_AUTH_KEY__|$(openssl rand -hex 32)|g" \
182        -e "s|__WORDPRESS_SECURE_AUTH_KEY__|$(openssl rand -hex 32)|g" \
183        -e "s|__WORDPRESS_LOGGED_IN_KEY__|$(openssl rand -hex 32)|g" \
184        -e "s|__WORDPRESS_NONCE_KEY__|$(openssl rand -hex 32)|g" \
185        -e "s|__WORDPRESS_AUTH_SALT__|$(openssl rand -hex 32)|g" \
186        -e "s|__WORDPRESS_SECURE_AUTH_SALT__|$(openssl rand -hex 32)|g" \
187        -e "s|__WORDPRESS_LOGGED_IN_SALT__|$(openssl rand -hex 32)|g" \
188        -e "s|__WORDPRESS_NONCE_SALT__|$(openssl rand -hex 32)|g" \
189        "$SCRIPT_DIR/templates/.env.example" > "$env_tmp"
190    chmod 0600 "$env_tmp"
191    mv "$env_tmp" .env
192else
193    warn 'Reusing existing .env; secrets will not be regenerated or printed.'
194fi
195chmod 0600 .env
196
197get_env() {
198    sed -n "s/^$1=//p" .env | tail -n 1
199}
200DOMAIN="$(get_env DOMAIN)"
201COMPOSE_PROJECT_NAME="$(get_env COMPOSE_PROJECT_NAME)"
202BLOG_PORT="$(get_env BLOG_PORT)"
203BLOG_SUBNET="$(get_env BLOG_SUBNET)"
204BLOG_GATEWAY="$(get_env BLOG_GATEWAY)"
205stored_http_port="$(get_env HTTP_PORT)"
206stored_https_port="$(get_env HTTPS_PORT)"
207if [[ -n "$stored_http_port" && -n "$EXPLICIT_HTTP_PORT" && "$stored_http_port" != "$EXPLICIT_HTTP_PORT" ]]; then
208    die 'HTTP_PORT conflicts with the existing .env value.'
209fi
210if [[ -n "$stored_https_port" && -n "$EXPLICIT_HTTPS_PORT" && "$stored_https_port" != "$EXPLICIT_HTTPS_PORT" ]]; then
211    die 'HTTPS_PORT conflicts with the existing .env value.'
212fi
213if [[ -n "$stored_http_port" ]]; then
214    HTTP_PORT="$stored_http_port"
215fi
216if [[ -n "$stored_https_port" ]]; then
217    HTTPS_PORT="$stored_https_port"
218fi
219if [[ -z "$stored_http_port" || -z "$stored_https_port" ]]; then
220    ports_tmp="$(mktemp '.env.ports.tmp.XXXXXX')"
221    cat .env > "$ports_tmp"
222    if [[ -z "$stored_http_port" ]]; then
223        printf 'HTTP_PORT=%s\n' "$HTTP_PORT" >> "$ports_tmp"
224    fi
225    if [[ -z "$stored_https_port" ]]; then
226        printf 'HTTPS_PORT=%s\n' "$HTTPS_PORT" >> "$ports_tmp"
227    fi
228    chmod 0600 "$ports_tmp"
229    mv "$ports_tmp" .env
230fi
231for key in MARIADB_DATABASE MARIADB_USER MARIADB_PASSWORD MARIADB_ROOT_PASSWORD \
232    WORDPRESS_AUTH_KEY WORDPRESS_SECURE_AUTH_KEY WORDPRESS_LOGGED_IN_KEY WORDPRESS_NONCE_KEY \
233    WORDPRESS_AUTH_SALT WORDPRESS_SECURE_AUTH_SALT WORDPRESS_LOGGED_IN_SALT WORDPRESS_NONCE_SALT; do
234    [[ -n "$(get_env "$key")" ]] || die "$key is missing from .env"
235done
236: "${BLOG_PORT:?BLOG_PORT is missing}"
237: "${BLOG_SUBNET:?BLOG_SUBNET is missing}"
238: "${BLOG_GATEWAY:?BLOG_GATEWAY is missing}"
239: "${COMPOSE_PROJECT_NAME:?COMPOSE_PROJECT_NAME is missing}"
240if [[ -n "$REQUESTED_DOMAIN" && "${REQUESTED_DOMAIN,,}" != "${DOMAIN,,}" ]]; then
241    die 'The requested domain differs from the existing .env domain.'
242fi
243validate_domain "$DOMAIN"
244validate_port BLOG_PORT "$BLOG_PORT"
245validate_port HTTP_PORT "$HTTP_PORT"
246validate_port HTTPS_PORT "$HTTPS_PORT"
247export DOMAIN COMPOSE_PROJECT_NAME BLOG_PORT BLOG_SUBNET BLOG_GATEWAY HTTP_PORT HTTPS_PORT
248
249computed_origin="https://${DOMAIN}"
250if [[ "$HTTPS_PORT" != '443' ]]; then
251    computed_origin="${computed_origin}:${HTTPS_PORT}"
252fi
253registered_origin="$(get_env PUBLIC_HTTPS_ORIGIN)"
254if [[ -n "$registered_origin" && "$registered_origin" != "$computed_origin" ]]; then
255    die 'PUBLIC_HTTPS_ORIGIN in .env does not match DOMAIN and HTTPS_PORT.'
256fi
257if [[ -z "$registered_origin" ]]; then
258    origin_tmp="$(mktemp '.env.origin.tmp.XXXXXX')"
259    cat .env > "$origin_tmp"
260    printf 'PUBLIC_HTTPS_ORIGIN=%s\n' "$computed_origin" >> "$origin_tmp"
261    chmod 0600 "$origin_tmp"
262    mv "$origin_tmp" .env
263fi
264PUBLIC_HTTPS_ORIGIN="$computed_origin"
265export PUBLIC_HTTPS_ORIGIN
266
267render_template() {
268    local source="$1"
269    local target="$2"
270    local mode="${3:-0644}"
271    [[ ! -L "$target" ]] || die "$target must not be a symbolic link."
272    if [[ -e "$target" && ! -f "$target" ]]; then
273        die "$target exists but is not a regular file."
274    fi
275    if [[ -f "$target" ]]; then
276        warn "Keeping existing $target"
277        return
278    fi
279    local temporary
280    temporary="$(mktemp "${target}.tmp.XXXXXX")"
281    sed \
282        -e "s|__DOMAIN__|$DOMAIN|g" \
283        -e "s|__BLOG_PORT__|$BLOG_PORT|g" \
284        -e "s|__BLOG_GATEWAY__|$BLOG_GATEWAY|g" \
285        -e "s|__HTTP_PORT__|$HTTP_PORT|g" \
286        -e "s|__HTTPS_PORT__|$HTTPS_PORT|g" \
287        -e "s|__PUBLIC_HTTPS_ORIGIN__|$PUBLIC_HTTPS_ORIGIN|g" \
288        "$source" > "$temporary"
289    chmod "$mode" "$temporary"
290    mv "$temporary" "$target"
291}
292
293mkdir -p nginx/logs php/conf.d php/php-fpm.d www
294render_template "$SCRIPT_DIR/templates/docker-compose.yml" docker-compose.yml
295render_template "$SCRIPT_DIR/templates/Dockerfile" Dockerfile
296render_template "$SCRIPT_DIR/templates/nginx/nginx.conf" nginx/nginx.conf
297render_template "$SCRIPT_DIR/templates/nginx/default.conf" nginx/default.conf
298render_template "$SCRIPT_DIR/templates/php/conf.d/99-blog.ini" php/conf.d/99-blog.ini
299render_template "$SCRIPT_DIR/templates/php/php-fpm.d/zz-blog.ini" php/php-fpm.d/zz-blog.ini
300created_wp_config=0
301if [[ ! -f www/wp-config.php ]]; then
302    created_wp_config=1
303fi
304render_template "$SCRIPT_DIR/templates/www/wp-config.php" www/wp-config.php 0640
305
306downloaded_wordpress=0
307if [[ ! -f www/index.php ]]; then
308    downloaded_wordpress=1
309    log 'Downloading WordPress into www/.'
310    download_dir="$(mktemp -d)"
311    curl -fsSL "$WORDPRESS_DOWNLOAD_URL" -o "$download_dir/wordpress.tar.gz"
312    tar -xzf "$download_dir/wordpress.tar.gz" -C "$download_dir"
313    cp -a "$download_dir/wordpress/." www/
314    rm -rf -- "$download_dir"
315else
316    warn 'Keeping the existing WordPress files in www/.'
317fi
318render_template "$SCRIPT_DIR/templates/www/wp-config.php" www/wp-config.php 0640
319if [[ "$downloaded_wordpress" == '1' ]]; then
320    chown -R 33:33 www
321    find www -type d -exec chmod 2775 {} +
322    find www -type f -exec chmod 0664 {} +
323fi
324if [[ "$created_wp_config" == '1' && -f www/wp-config.php ]]; then
325    chown 33:33 www/wp-config.php
326    chmod 0640 www/wp-config.php
327fi
328
329compose() {
330    docker compose --project-name "$COMPOSE_PROJECT_NAME" --env-file .env \
331        -f docker-compose.yml "$@"
332}
333
334log 'Validating the Compose model.'
335compose config -q
336if [[ "$PULL_IMAGES" == '1' ]]; then
337    log 'Pulling Docker images.'
338    compose pull db redis nginx
339fi
340log 'Building and starting the WordPress containers.'
341compose up -d --build
342
343for service_name in db redis php nginx; do
344    container_name="${COMPOSE_PROJECT_NAME}-${service_name}"
345    healthy=0
346    for attempt in $(seq 1 60); do
347        status="$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container_name" 2>/dev/null || true)"
348        if [[ "$status" == 'healthy' ]]; then
349            healthy=1
350            break
351        fi
352        sleep 5
353    done
354    [[ "$healthy" == '1' ]] || die "$container_name did not become healthy."
355done
356
357http_code="$(curl -sS --max-time 30 -o /dev/null -w '%{http_code}' \
358    -H "Host: $DOMAIN" -H 'X-Forwarded-Proto: https' "http://127.0.0.1:${BLOG_PORT}/wp-admin/install.php")"
359[[ "$http_code" == '200' ]] || die "WordPress origin returned HTTP $http_code."
360printf 'WORDPRESS_ORIGIN_HTTP=%s\n' "$http_code"
361
362mkdir -p "$CADDY_CONFIG_ROOT/sites.d"
363main_caddyfile="$CADDY_CONFIG_ROOT/Caddyfile"
364site_caddyfile="$CADDY_CONFIG_ROOT/sites.d/${DOMAIN}.conf"
365import_line="import ${CADDY_CONFIG_ROOT}/sites.d/*.conf"
366custom_ports=0
367if [[ "$HTTP_PORT" != '80' || "$HTTPS_PORT" != '443' ]]; then
368    custom_ports=1
369fi
370
371if [[ -f "$site_caddyfile" ]]; then
372    warn "Keeping existing Caddy site config: $site_caddyfile"
373else
374    if [[ -f "$main_caddyfile" ]] && grep -Fq "$DOMAIN" "$main_caddyfile"; then
375        die 'The domain already appears in the main Caddyfile; review it before continuing.'
376    fi
377    if [[ "$custom_ports" == '1' ]]; then
378        render_template "$SCRIPT_DIR/templates/Caddyfile.site-custom" "$site_caddyfile"
379    else
380        render_template "$SCRIPT_DIR/templates/Caddyfile.site" "$site_caddyfile"
381    fi
382fi
383
384if [[ ! -f "$main_caddyfile" ]]; then
385    main_tmp="$(mktemp "${main_caddyfile}.tmp.XXXXXX")"
386    if [[ "$custom_ports" == '1' ]]; then
387        printf '{\n\tauto_https disable_redirects\n\thttp_port %s\n\thttps_port %s\n}\n\n%s\n' \
388            "$HTTP_PORT" "$HTTPS_PORT" "$import_line" > "$main_tmp"
389    else
390        printf '%s\n' "$import_line" > "$main_tmp"
391    fi
392    chmod 0644 "$main_tmp"
393    mv "$main_tmp" "$main_caddyfile"
394elif ! grep -Fxq "$import_line" "$main_caddyfile"; then
395    if [[ "$custom_ports" == '1' ]]; then
396        die 'Custom ports require a recognized isolated Caddyfile; refusing to alter an existing global configuration.'
397    fi
398    main_tmp="$(mktemp "${main_caddyfile}.tmp.XXXXXX")"
399    cp -a "$main_caddyfile" "${main_caddyfile}.backup-$(date -u +%Y%m%dT%H%M%SZ)"
400    cat "$main_caddyfile" > "$main_tmp"
401    printf '\n%s\n' "$import_line" >> "$main_tmp"
402    chmod 0644 "$main_tmp"
403    caddy validate --config "$main_tmp" --adapter caddyfile
404    mv "$main_tmp" "$main_caddyfile"
405fi
406
407log 'Validating the complete host Caddy configuration.'
408caddy validate --config "$main_caddyfile" --adapter caddyfile
409
410if [[ "$CADDY_CONFIG_ROOT" != '/etc/caddy' && "$SKIP_SERVICE_ACTIONS" != '1' ]]; then
411    die 'A custom CADDY_CONFIG_ROOT requires SKIP_SERVICE_ACTIONS=1 to avoid touching the system Caddy service.'
412fi
413if [[ "$SKIP_SERVICE_ACTIONS" != '1' ]]; then
414    systemctl enable --now caddy
415    systemctl reload-or-restart caddy
416fi
417
418if [[ "$SKIP_SERVICE_ACTIONS" != '1' ]]; then
419    connect_ip='127.0.0.1'
420    curl_insecure=()
421    if [[ "$DOMAIN" == 'localhost' ]]; then
422        curl_insecure=(-k)
423    fi
424    public_port=''
425    if [[ "$HTTPS_PORT" != '443' ]]; then
426        public_port=":$HTTPS_PORT"
427    fi
428    public_http_port=''
429    if [[ "$HTTP_PORT" != '80' ]]; then
430        public_http_port=":$HTTP_PORT"
431    fi
432    https_code="$(curl "${curl_insecure[@]}" -L -sS --max-time 30 \
433        --resolve "${DOMAIN}:${HTTPS_PORT}:${connect_ip}" \
434        -o /dev/null -w '%{http_code}' "https://${DOMAIN}${public_port}/")"
435    [[ "$https_code" == '200' ]] || die "Public HTTPS returned HTTP $https_code."
436    expected_redirect="${PUBLIC_HTTPS_ORIGIN}/wp-admin/install.php"
437    redirect_result="$(curl -sS --max-time 20 \
438        --resolve "${DOMAIN}:${HTTP_PORT}:${connect_ip}" \
439        -o /dev/null -w '%{http_code} %{redirect_url}' \
440        "http://${DOMAIN}${public_http_port}/wp-admin/install.php")"
441    [[ "${redirect_result%% *}" == '308' ]] || die 'Unexpected HTTP redirect status.'
442    [[ "${redirect_result#* }" == "$expected_redirect" ]] || die 'Unexpected HTTP redirect target.'
443    printf 'PUBLIC_HTTPS_HTTP=%s\n' "$https_code"
444    printf 'HTTP_REDIRECT=%s\n' "${redirect_result#* }"
445fi
446
447printf '\n\033[1;32m[SUCCESS]\033[0m Deployment is complete.\n'
448printf 'WordPress directory: %s\n' "$INSTALL_DIR"
449printf 'Caddy configuration: %s\n' "$main_caddyfile"
450printf 'Website: %s\n' "$PUBLIC_HTTPS_ORIGIN"
451printf 'Finish setup: %s/wp-admin/install.php\n' "$PUBLIC_HTTPS_ORIGIN"
452printf 'Manage containers: cd %s && docker compose ps\n' "$INSTALL_DIR"
453if [[ "$SKIP_SERVICE_ACTIONS" == '1' ]]; then
454    printf 'Host Caddy was validated but not started. Start it with: caddy run --config %s\n' "$main_caddyfile"
455fi
Docker + Caddy 部署 WordPress 实战
无责任编辑
大海
发布时间
2026 年 11 月 16 日
最后编辑时间
2026 年 11 月 16 日
版权协议