nginx容器与php-fpm容器连接方式
文档说明:只记录关键地方;
提示: 不要把容器当作虚拟机使用,每个容器都有自己独有的功能
nginx 容器与PHP容器连接
容器之间网络默认使用 桥接 的方式连接
如果是K8S,nginx配置 fastcgi_pass 127.0.0.1:9000 这里不用修改
version: "3"
services:
nginx-web:
image: nginx:alpine
container_name: nginx-web-server
ports:
- "80:80"
depends_on:
- php-fpm
volumes:
- ./web/:/usr/share/nginx/html/
- ./default.conf:/etc/nginx/conf.d/default.conf
php-fpm:
image: docker.io/wenba100xie/php:7.4-fpm-alpine-20221030T214057Z
container_name: php-fpm-server
expose:
- 9000
volumes:
- ./web/:/usr/share/nginx/html/
- ./www.conf:/usr/local/etc/php-fpm.d/www.conf
启动、关闭、查看日志
# 启动
docker-compose -f docker-compose.yaml up -d
# 关闭
docker-compose -f docker-compose.yaml down --remove-orphans
# 查看日志
docker-compose -f docker-compose.yaml logs -f
获得nginx和php基础镜像的内默认配置文件
从容器镜像中拷贝文件到容器外
#!/bin/bash
set -eux
__DIR__=$(
cd "$(dirname "$0")"
pwd
)
cd ${__DIR__}
mkdir -p conf
image=nginx:alpine
container_id=$(docker create $image) # returns container ID
docker cp $container_id:/etc/nginx/nginx.conf conf/nginx-default.conf
docker cp $container_id:/etc/nginx/conf.d/default.conf conf/nginx-default-domain.conf
docker rm $container_id
image=docker.io/wenba100xie/php:7.4-fpm-alpine-20221030T212904Z
container_id=$(docker create $image) # returns container ID
docker cp $container_id:/usr/local/etc/php-fpm.conf conf/7.4-fpm-alpine-php-fpm.conf
docker cp $container_id:/usr/local/etc/php/php.ini-production conf/7.4-fpm-alpine-php.ini
docker cp $container_id:/usr/local/etc/php-fpm.d/www.conf conf/7.4-fpm-alpine-www.conf
docker rm $container_id
cp conf/nginx-default-domain.conf default.conf
cp conf/7.1-fpm-alpine-www.conf www.conf
修改配置: nginx 配置 关键点
/etc/nginx/conf.d/default.conf
root /usr/share/nginx/html;
location /
index index.html index.htm index.php;
}
location ~* \.php$ {
fastcgi_index index.php;
# fastcgi_pass 127.0.0.1:9000;
fastcgi_pass php-fpm:9000; # 关键点:使用服务名称连接,而不是IP;如果不想修改这里,想使用127.0.0.1 那就修改网络模式,为共享容器网络
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
修改配置: php-fpm配置 关键点
/usr/local/etc/php-fpm.d/www.conf
; listen = 127.0.0.1:9000 ; 注释默认配置,变更为下面配置
listen = 9000 ;这里是配置关键点
最简单的容器连接配置是这样
网络模式使用 service:pause
所有容器共享一个网络,也就是容器与容器之间直接可以用localhost也可以使用127.0.0.1
version: "3"
services:
pause:
# image: gcr.io/google-containers/pause-amd64:3.1
image: alpine:latest
restart: always
container_name: pause
command: [ 'tail', '-f','/dev/null' ]
ports:
- "80:80"
- "443:443"
nginx:
image: nginx:alpine
network_mode: 'service:pause'
depends_on:
- pause
php-fpm:
image: php:7.4-fpm-alpine
depends_on:
- pause
network_mode: 'service:pause'