同一主机下的不同服务间访问
最近又部署了一个前后端分离项目,但是还是学艺不精,折腾了半天
最后一个遇到的问题就是,前端容器启动了,但是始终无法连接后端的接口
版本1
这是当时的配置信息
# nginx
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
location /prod-api/ {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://{公网ip}:28080/;
client_max_body_size 1024m;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
# docker-compose
services:
api:
container_name: malan_api
image: malan-api:latest
ports:
- "28080:28080"
environment:
- ...
volumes:
- "./api/upload:/upload"
restart: "unless-stopped"
ui:
container_name: malan_ui
image: malan-ui:latest
ports:
- "11780:80"
volumes:
- "./ui/nginx.conf:/etc/nginx/nginx.conf"
restart: "unless-stopped"
这个情况下需要开放公网的ip端口之后才能访问
版本2
# nginx
...
location /prod-api/ {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:28080/;
client_max_body_size 1024m;
}
...
nginx.conf
不变
主要就是转发的ip改了 因为我不想对外直接开放后端的接口 但是这样一直访问不了
我对其原因非常好奇(发现自己好蠢)
- 容器内的127.0.0.1指向容器自身,而不是主机。如果你想从容器访问主机服务,可以使用主机的IP地址,或者在Docker for Windows和Mac中,使用
host.docker.internal
来访问主机。
版本3
# nginx
...
location /prod-api/ {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://malan_api:28080/;
client_max_body_size 1024m;
}
...
直接使用服务名访问 太好了 既不用开放端口 也可以访问
标签:容器,set,http,nginx,访问,header,api,proxy From: https://www.cnblogs.com/yuqiu2004/p/18489664