我一直在尝试使用 docker 在 nginx 上运行我的 Angular 应用程序,但我无法运行它。这是我尝试的最后修改:
我的 Docker 文件:
FROM node:latest as build
WORKDIR /usr/local/app
COPY package.json .
COPY . .
RUN npm install
RUN npm install @angular/cli@17
CMD ["npm", "start"]
EXPOSE 4200
我的 docker-compose.yaml 文件:
version: "3"
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;
}
}
我用来运行我的撰写文件的命令:
docker-compose up --build
尝试连接时出现的错误:
我无法克服
看起来你的 Angular 应用程序只接受来自本地主机的连接,因为它位于容器中,这意味着它只接受来自容器内的连接。
您还需要允许它接收来自外部的请求。您可以更新
npm start
命令来执行此操作。
合适的
package.json
可能看起来像这样:
{
"name": "test",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --host 0.0.0.0",
"build": "ng build --configuration=production"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/cli": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/platform-server": "^17.3.0",
"@angular/router": "^17.3.0",
"@angular/ssr": "^17.3.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.3.0",
"@angular/cli": "^17.3.0",
"@angular/compiler-cli": "^17.3.0",
"@types/express": "^4.17.17",
"@types/node": "^18.18.0",
"typescript": "~5.4.2"
}
}
你可以忽略其中的大部分。关键位是启动脚本的定义,应该类似于
ng serve --host 0.0.0.0
,其中 --host 0.0.0.0
参数是关键位!