部署过才发现,使用Docker部署PHP网站,没想象中的简单。顺便总结一下使用Docker Compose部署Typecho的经验。
1. 概述
重点注意:
- 一般PHP网站的Docker镜像,只提供了网站的PHP源码和
php-fpm
服务,在生产环境不能单独部署。 - 生产环境需要前端搭配Nginx或Apache等接收请求,再交给
php-fpm
服务处理。一般还需要后端连上MySQL、MariaDB、PostgreSQL等数据库。 - 建议使用Docker Compose部署。比Docker run更好管理,比K8S更省资源。
2. 建立网络
建议先建立一个Docker网络,把相关服务部署到该网络。
- 所有服务使用
service
名称作为host名称,配置相互访问时不用填IP。 - 同一网络内的服务,不用在宿主机暴露端口,各个服务之间也相互访问。一般只需暴露Nginx的端口。
建立Docker网络的参考命令如下。其中网络名称为docker-net
。
docker network create --driver "bridge" docker-net
3. Nginx服务
Nginx的docker-compose.yaml
,路径在/opt/docker_deploy/nginx/
,内容如下:
services:
nginx:
image: nginx:1.27.0-alpine
restart: always
ports:
- 80:80
- 443:443
environment:
- NGINX_PORT=80
volumes:
- ./etc/nginx.conf/:/etc/nginx/nginx.conf:ro
- ./etc/conf.d:/etc/nginx/conf.d
- /etc/letsencrypt/archive:/etc/nginx/cert:ro
- ./logs:/var/log/nginx
- ./www:/var/www
- /opt/docker_deploy/typecho/app:/var/www/typecho:ro
networks:
- docker-net
networks:
docker-net:
external: true
Type的Nginx配置文件,在/opt/docker_deploy/nginx/etc/conf.d/typecho.conf
,内容如下:
server {
server_name blog.xxxx.com;
listen 80;
rewrite ^(.*)$ https://$host$1 permanent;
}
server {
server_name blog.xxxx.com;
listen 443 ssl;
http2 on;
index index.php index.htm index.html;
root /var/www/typecho;
ssl_certificate /etc/nginx/cert/blog.xxxx.com/fullchain8.pem;
ssl_certificate_key /etc/nginx/cert/blog.xxxx.com/privkey8.pem;
add_header X-Frame-Options SAMEORIGIN;
add_header Content-Security-Policy "frame-ancestors 'self';";
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
include fastcgi_params;
#fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_FILENAME /app$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_pass typecho:9000;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
}
location / {
try_files $uri $uri/ /index.php$is_args$query_string;
}
}
4. Typecho
部署要点:
Typecho的docker-compose.yaml
,路径在/opt/docker_deploy/typecho/
,内容如下:
ervices:
typecho:
image: joyqi/typecho:1.2.1-php8.0-fpm-alpine
restart: always
#ports:
# - "9000:9000"
environment:
- "TYPECHO_SITE_URL=https://blog.xxxx.com"
- "TYPECHO_DB_ADAPTER=Pdo_Mysql"
- "TYPECHO_DB_HOST=mariadb"
- "TYPECHO_DB_PORT=3306"
- "TYPECHO_DB_USER=typecho"
- "TYPECHO_DB_PASSWORD=123456"
- "TYPECHO_DB_DATABASE=typecho"
volumes:
- ./app:/app
networks:
- docker-net
networks:
docker-net:
external: true
要注意,如果Nginx的Typecho没有开启SSL,但需要全局https访问Typecho,可以在配置文件config.inc.php
添加以下配置:
/** 全站开启https */
define('__TYPECHO_SECURE__', true);
5. MariaDB
MariaDB的docker-compose.yaml
,路径在/opt/docker_deploy/mariadb/
,内容如下:
ervices:
mariadb:
image: mariadb:11.4.2
restart: always
#ports:
# - 3306:3306
volumes:
- ./dbdata:/var/lib/mysql
environment:
MARIADB_ROOT_PASSWORD: root123456
#MYSQL_USER: ${DB_USER}
#MYSQL_PASSWORD: ${DB_PASSWORD}
#MYSQL_DATABASE: ${DB_DATABASE}
networks:
- docker-net
networks:
docker-net:
external: true