Docker搭建WordPress并绑定域名教程(一)

这一节我们讲如何通过Docker搭建WordPress并绑定域名,步骤如下:


步骤1:配置域名DNS解析

  1. 登录你的域名注册商(如GoDaddy、阿里云等),进入DNS管理界面。
  2. 添加一条 A记录,将域名指向你的服务器公网IP。
    • 例如:@www 指向 123.123.123.123(你的服务器IP)。
  3. 等待DNS生效(通常几分钟到几小时),可通过 ping yourdomain.com 测试是否解析成功。

步骤2:确保Docker容器端口映射正确

  • 启动WordPress容器时,确保将容器的80/443端口映射到宿主机:
    docker run -d \
    --name wordpress \
    -p 80:80 \
    -p 443:443 \
    -e WORDPRESS_DB_HOST=mysql \
    -e WORDPRESS_DB_USER=root \
    -e WORDPRESS_DB_PASSWORD=your_password \
    wordpress:latest

    提示:如果使用其他端口(如8080),需通过反向代理转发(见步骤3)。


步骤3:配置反向代理(推荐Nginx)

  1. 安装Nginx
    sudo apt update && sudo apt install nginx
  2. 创建Nginx配置文件
    • /etc/nginx/sites-available/yourdomain.com 创建文件,内容如下:
      server {
       listen 80;
       server_name yourdomain.com www.yourdomain.com;
      
       location / {
           proxy_pass http://localhost:80;  # 如果WordPress容器端口映射到宿主机的80
           proxy_set_header Host $host;
           proxy_set_header X-Real-IP $remote_addr;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header X-Forwarded-Proto $scheme;
       }
      }
  3. 启用配置并重启Nginx
    sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
    sudo nginx -t  # 测试配置
    sudo systemctl restart nginx

步骤4:更新WordPress站点地址

  1. 进入WordPress后台:访问 http://yourdomain.com/wp-admin
  2. 转到 设置 → 常规,修改以下两项为你的域名:
    • WordPress地址(URL)https://yourdomain.com
    • 站点地址(URL)https://yourdomain.com
  3. 保存更改。

步骤5:配置HTTPS(SSL证书)

  1. 使用Certbot自动获取证书
    sudo apt install certbot python3-certbot-nginx
    sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
  2. Certbot会自动修改Nginx配置,启用HTTPS并强制跳转。

步骤6:处理Docker专用网络(可选)

  • 如果使用Docker Compose且包含独立网络(如nginx-proxy),可在docker-compose.yml中添加环境变量:
    services:
    wordpress:
      environment:
        - VIRTUAL_HOST=yourdomain.com
        - LETSENCRYPT_HOST=yourdomain.com
        - [email protected]

常见问题排查

  • DNS未生效:使用 dig yourdomain.com 检查解析结果。
  • 端口冲突:确保宿主机80/443端口未被占用(sudo lsof -i :80)。
  • WordPress重定向错误:清除浏览器缓存或更新.htaccess文件。
  • 混合内容警告:确保站点URL为https://,并安装插件(如Really Simple SSL)。

完成以上步骤后,你的WordPress应能通过域名正常访问。如有问题,检查Docker日志(docker logs wordpress)和Nginx错误日志(/var/log/nginx/error.log)。

This entry was posted in 网络相关 and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *