如果您的Nginx和php-fpm容器位于同一主机上,则可以在主机上配置一个供nginx容器使用的小型dnsmasq实例,并运行一个脚本,以在容器的IP地址包含以下内容时自动更新DNS记录改变了。
我编写了一个小脚本来执行此操作(粘贴在下面),该脚本会自动更新与容器名称相同的DNS记录,并将它们指向容器的IP地址:
#!/bin/bash
# 10 seconds interval time by default
INTERVAL=${INTERVAL:-10}
# dnsmasq config directory
DNSMASQ_CONFIG=${DNSMASQ_CONFIG:-.}
# commands used in this script
DOCKER=${DOCKER:-docker}
SLEEP=${SLEEP:-sleep}
TAIL=${TAIL:-tail}
declare -A service_map
while true
do
changed=false
while read line
do
name=${line##* }
ip=$(${DOCKER} inspect --format '{{.NetworkSettings.IPAddress}}' $name)
if [ -z ${service_map[$name]} ] || [ ${service_map[$name]} != $ip ] # IP addr changed
then
service_map[$name]=$ip
# write to file
echo $name has a new IP Address $ip >&2
echo "host-record=$name,$ip" > "${DNSMASQ_CONFIG}/docker-$name"
changed=true
fi
done < <(${DOCKER} ps | ${TAIL} -n +2)
# a change of IP address occured, restart dnsmasq
if [ $changed = true ]
then
systemctl restart dnsmasq
fi
${SLEEP} $INTERVAL
done
然后,使用来启动您的nginx容器--dns host-ip-address
,其中host-ip-address
是接口上主机的IP地址docker0
。
您的Nginx配置应动态解析名称:
server {
resolver host-ip-address;
listen 80;
server_name @server_name@;
root /var/www/@root@;
index index.html index.htm index.php;
location ~ ^(.+?\.php)(/.*)?$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$1;
set $backend "@fastcgi_server@";
fastcgi_pass $backend;
}
}
参考文献:
如果您的nginx和php-fpm位于不同的主机上,则可以尝试@smaj的答案。