Nginx容器和php-fpm容器通信
容器如何获取宿主机docker0网卡IP?
下面2条命令是等效的
--add-host host:$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+') \
--add-host host:$(/sbin/ip route|awk '/docker0/ { print $9}') \
下面2条命令是等效的
-e DOCKER_HOST=$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+') \
-e DOCKER_HOST=$(/sbin/ip route|awk '/docker0/ { print $9}') \
docker pull nginx;
docker pull devilbox/php-fpm:5.6-prod
docker run -d --name php -p 9000:9000 \
-e DOCKER_LOGS=1 \
-e FORWARD_PORTS_TO_LOCALHOST='3306:172.31.0.18:3306' \
-v $PWD/www:/var/www/default/htdocs \
-v $PWD/logs:/var/log/php \
devilbox/php-fpm:5.6-prod
docker run -d --name nginx_80 -p 80:80 \
--add-host host:$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+') \
-v $PWD/www:/tol/nginx/www \
-v $PWD/conf/nginx.conf:/etc/nginx/nginx.conf:ro \
-v $PWD/conf/conf.d:/etc/nginx/conf.d:ro \
-v $PWD/logs:/var/log/nginx \
--volumes-from php \
-u root nginx
注意:nginx并没有link php容器,但通信前提是:php容器端口要绑定到宿主机9000端口上
Nginx配置文件(部分)
server {
listen 80;
server_name bbs.i5i5.top;
root /var/www/default/htdocs/bbs/ROOT; #此目录是php容器的应用程序目录,通过共享券的方式,nginx容器也可以访问到
index index.html index.jsp index.htm index.php;
location ~ .*\.(gif|jpg|jpeg|png|bmp|ico|swf|js|css)$ {
expires 1h; #缓存到客户端的浏览器一个小时
}
location ~ \.php$ {
fastcgi_pass host:9000; #容器间通信:nginx会查找容器内/etc/profile文件找的host映射的ip地址
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
access_log /var/log/nginx/bbs.log access;
}
题外话
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
nginx会把获取的请求参数通过上面的配置转发给php-fpm服务处理,其中$document_root表示的是应用程序路径,取root /var/www/default/htdocs/bbs/ROOT; 的值。
下面2种配置方式是等效的:
root /var/www/default/htdocs/bbs/ROOT;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_FILENAME /var/www/default/htdocs/bbs/ROOT$fastcgi_script_name;
命令1:
ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+'
命令2:
/sbin/ip route|awk '/docker0/ { print $9}'
用法
docker run -d --name nginx_80 -p 80:80 \
--add-host host:$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+') \
--add-host host2:$(/sbin/ip route|awk '/docker0/ { print $9}') \
-e DOCKER_HOST=$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+') \
-e DOCKER_HOST2=$(/sbin/ip route|awk '/docker0/ { print $9}') \
-v $PWD/www:/tol/nginx/www \
-v $PWD/conf/nginx.conf:/etc/nginx/nginx.conf:ro \
-v $PWD/conf/conf.d:/etc/nginx/conf.d:ro \
-v $PWD/logs:/var/log/nginx \
--volumes-from php \
-u root nginx
容器内部,获取宿主机docker0 IP的方式
1.通过容器host文件
cat /etc/profile
172.17.0.3 host
172.17.0.3 host2
2.通过容器环境变量
echo $DOCKER_HOST
打印:172.17.0.3
echo $DOCKER_HOST2
打印:172.17.0.3