我在 Docker 中的同一个端口上运行了两个服务(后端和 API)。但是,每当我发送请求时,NGINX 都会将所有请求路由到后端服务,而我无法正常访问 API 服务。
我怀疑这是我的 NGINX 配置的问题。
这是我的文件:
docker-compose.yml
version: '3.8'
services:
backend:
build:
context: .
dockerfile: ./backend/Dockerfile.dev
volumes:
- ./backend:/var/www/html/backend
environment:
- APP_ENV=development
networks:
- bysooq-network
expose:
- 9000
env_file:
- .env
api:
build:
context: .
dockerfile: ./api/Dockerfile.dev
volumes:
- ./api:/var/www/html/api
environment:
- APP_ENV=development
networks:
- bysooq-network
expose:
- 9000
env_file:
- .env
postgres:
image: postgres:13
restart: always
volumes:
- ~/bysooq-data/postgres:/var/lib/postgresql/data
environment:
POSTGRES_DB: xxx
POSTGRES_USER: xx
POSTGRES_PASSWORD: xxx
networks:
- bysooq-network
redis:
image: redis:latest
ports:
- "6380:6379"
restart: always
networks:
- bysooq-network
nginx:
image: nginx:latest
volumes:
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
- ./api:/var/www/html/api
- ./backend:/var/www/html/backend
ports:
- 80:80
depends_on:
- backend
- api
networks:
- bysooq-network
networks:
bysooq-network:
driver: bridge
nginx 默认配置文件
nginx
server {
listen 80;
server_name localhost;
client_max_body_size 100M;
index index.php;
# API Service - Must come first with strict matching
location ~ ^/api(/.*)?$ {
root /var/www/html/api/web;
try_files $1 $1/ /index.php$is_args$args;
location ~ \.php$ {
fastcgi_pass api:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
fastcgi_param REQUEST_URI $1$is_args$args;
}
}
# Backend Service
location / {
root /var/www/html/backend/web;
try_files $uri $uri/ /index.php$is_args$args;
location ~ \.php$ {
fastcgi_pass backend:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
}
我的期望是:
对 /api/* 的请求应该转到 api 服务。
其他请求应该转到后端服务。
会发生什么:
所有请求(甚至 /api/...)都由后端处理。
问题:如何正确配置 NGINX 以将 /api/* 请求路由到 API 服务并将其他请求路由到后端服务?
提前致谢!