Docker容器间通信与Nginx反向代理部署方案
以部署Ghost博客为例,在VPS服务器上通过Docker运行两个独立的Ghost博客实例,并配置一个Nginx作为反向代理服务器,负责将两个不同的域名请求分别指向这两个博客实例。
Docker启动命令配置
Ghost实例配置
docker run -e NODE_ENV=production --name ghost1 -v /path/to/data/ghost/ghost1/:/var/lib/ghost -d ghost
docker run -e NODE_ENV=production --name ghost2 -v /path/to/data/ghost/ghost2/:/var/lib/ghost -d ghost
Nginx实例配置
复制代码 代码如下: docker run -p 80:80 --name nginx --link ghost1 --link ghost2 -v /path/to/data/nginx/nginx.conf:/etc/nginx/nginx.conf -d nginx
首先启动两个Ghost容器,随后启动Nginx容器。在启动Nginx时使用--link参数将其与ghost1和ghost2建立连接。该参数会自动在Nginx容器中注入相关环境变量,并在其/etc/hosts文件中添加对应容器名称到IP地址的映射记录。
root@fabfd4bacfda:/# cat /etc/hosts
172.17.0.3 ghost1 d19c0134011a
172.17.0.5 ghost2 0e2e66ba70e0
172.17.0.4 fabfd4bacfda
Nginx反向代理设置
编辑nginx.conf配置文件,在http配置段内添加相应的服务器配置内容。
http {
server {
listen 80;
server_name www.domain1.tk domain1.tk;
location / {
proxy_pass http://ghost1:2368;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen 80;
server_name www.domain2.tk domain2.tk;
location / {
proxy_pass http://ghost2:2368;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
需注意proxy_pass指令的值,例如proxy_pass http://ghost2:2368;。这里的ghost2并非外部域名,而是Nginx容器/etc/hosts文件中由--link参数自动生成的主机名条目。
完成上述配置后,Nginx即可根据接收到的域名请求,将流量分别代理转发至对应的Ghost博客实例中。
补充说明
容器重启后其内部IP地址可能会发生变化,因此直接在nginx.conf中硬编码IP地址并非最佳实践。采用--link方式时,/etc/hosts文件会随容器IP的动态变化自动更新,因此使用容器名(域名)进行代理是更易于维护的方案。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。