我一直在尝试使用 Docker 在 NGINX 上托管 Angular 应用程序,但是当我构建容器并转到 localhost:8080 时,我收到 502 Bad Gateway 错误。
这是我的
Dockerfile
:
FROM node:latest as build
WORKDIR /usr/local/app
COPY ./ /usr/local/app/
RUN npm install
RUN npm install -g @angular/cli
CMD ["npm", "start"]
FROM nginx:latest
RUN rm /usr/share/nginx/html/*
COPY --from=build /usr/local/app/dist/prueba /usr/share/nginx/html
RUN rm etc/nginx/conf.d/default.conf
COPY default.conf /etc/nginx/conf.d/
EXPOSE 80
这是我的
default.conf
文件:
server {
listen 80;
server_name app;
location / {
proxy_pass http://localhost:4200;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
这是我用来构建图像的线:
docker build -t front .
这是我用来运行图像的行:
docker run -d -p 8080:80 front
我不知道该怎么办,我要疯了。
看起来您想同时运行 Angular 服务器和 NGINX。理想情况下,每个容器应该只有一个进程。
所以我建议使用 Docker Compose 来实现此目的。
创建一个
docker-compose.yml
:
version: "3.9"
services:
app:
container_name: app
build:
context: .
nginx:
container_name: nginx
image: nginx
ports:
- "80:80"
depends_on:
- app
volumes:
- ./default.conf:/etc/nginx/conf.d/default.conf
有两项服务:
更新您的
default.conf
:
server {
listen 80;
server_name app;
location / {
proxy_pass http://app:4200;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
请注意,
proxy_pass
行指的是在 app
服务上运行的端口 4200。
最后将您的
Dockerfile
更新为:
FROM node:latest as build
WORKDIR /usr/local/app
COPY package.json .
RUN npm install
COPY . .
CMD ["npm", "start"]
运行:
docker-compose up --build