使用Docker部署WordPress:如何避免wp-content/index.php在容器启动时被覆盖?
使用Docker部署WordPress:如何避免wp-content/index.php在容器启动时被覆盖?
嘿,这个问题我之前踩过坑!其实罪魁祸首是官方WordPress Docker镜像自带的启动脚本(entrypoint.sh)——容器每次启动时,它会自动把镜像里默认的wp-content目录内容同步到你挂载的本地目录里,哪怕你本地已经有index.php,也会被镜像里的默认文件给覆盖掉。下面给你几个实用的解决办法,按简单到复杂排序:
1. 单独挂载index.php和子目录,而非整个wp-content
这是最省心的办法!不用改脚本也不用构建镜像,只要调整docker-compose.yml里的挂载规则:
原来你是把整个wp-content目录挂载进去,现在改成只挂载plugins、themes和index.php这几个你需要管控的部分:
services: wordpress: image: wordpress:latest volumes: # 单独挂载需要自定义的文件和目录 - ./wp-content/index.php:/var/www/html/wp-content/index.php - ./wp-content/plugins:/var/www/html/wp-content/plugins - ./wp-content/themes:/var/www/html/wp-content/themes - ./wp-config.php:/var/www/html/wp-config.php # 其他配置(端口、环境变量等)保持不变
这样容器里的wp-content基础结构还是用镜像自带的,但关键的index.php和你的插件、主题都由本地文件接管,启动脚本不会覆盖挂载进来的单个文件,完美解决问题。
2. 自定义Docker镜像,替换默认的index.php
如果你的index.php需要长期保持自定义,也可以自己构建一个专属的WordPress镜像,把你的index.php预先放进镜像里:
- 在项目根目录创建
Dockerfile,内容如下:
FROM wordpress:latest # 把本地的wp-content/index.php复制到镜像的默认模板目录 COPY wp-content/index.php /usr/src/wordpress/wp-content/index.php
- 修改
docker-compose.yml,使用你构建的镜像:
services: wordpress: # 替换成你构建的镜像名,比如my-custom-wordpress build: . volumes: - ./wp-content:/var/www/html/wp-content - ./wp-config.php:/var/www/html/wp-config.php # 其他配置不变
- 执行
docker-compose build构建镜像,之后启动容器就会用你自定义的index.php作为模板,哪怕启动脚本同步内容,覆盖的也是你自己的版本,不会丢失Git跟踪的修改。
3. 改写启动脚本,跳过index.php的同步
如果上面的办法都不满足你的需求,还可以直接修改镜像的启动脚本,让它跳过index.php的复制:
- 在项目根目录创建一个
custom-entrypoint.sh文件,内容如下(基于官方脚本修改,跳过index.php的同步):
#!/bin/bash set -e # 复制wp-content下的所有文件,但排除index.php cp -r /usr/src/wordpress/wp-content/* /var/www/html/wp-content/ --exclude=index.php # 执行官方entrypoint的剩余逻辑 exec docker-entrypoint.sh apache2-foreground
- 给脚本添加执行权限:
chmod +x custom-entrypoint.sh - 修改
docker-compose.yml,挂载并使用这个自定义启动脚本:
services: wordpress: image: wordpress:latest volumes: - ./wp-content:/var/www/html/wp-content - ./wp-config.php:/var/www/html/wp-config.php - ./custom-entrypoint.sh:/usr/local/bin/custom-entrypoint.sh entrypoint: ["bash", "/usr/local/bin/custom-entrypoint.sh"] # 其他配置不变
这样启动脚本就只会同步wp-content下的其他文件,完全跳过index.php,你的本地文件就能安全保留了。
内容来源于stack exchange
相关产品推荐
相关产品推荐

