【问题标题】:Get a 404 Not Found from nginx when ng buildng build 时从 nginx 获取 404 Not Found
【发布时间】:2020-02-18 12:01:34
【问题描述】:

我是角度新手。我尝试在 docker 中运行我的 Angular 应用程序。

当我执行ng buildng build -prod 并尝试使用此 dockerfile 让它在 docker 中运行时:

### STAGE 1: Build ###
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
COPY --from=build /usr/src/app/dist/TBH-GUI /usr/share/nginx/html

我的起始页显示正确。在这个起始页上,我有一些指向其他组件的链接。当我点击链接时,我得到一个404 Not Found nginx/1.17.1

我想我的构建过程有误。

我的package.json

{
  "name": "tbh-gui",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.1",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "~9.0.2",
    "@angular/compiler-cli": "~9.0.1",
    "@angular/language-service": "~9.0.1",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5"
  }
}

我的angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "TBH-GUI": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/TBH-GUI",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "TBH-GUI:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "TBH-GUI:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "TBH-GUI:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "TBH-GUI:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "TBH-GUI:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "TBH-GUI"
}

我的项目结构:

我的 nginx.conf:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}


#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
# 
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

【问题讨论】:

  • 您正在使用 ngnix,所以您可以使用发布您的 ngnix 配置。
  • @RatnadeepBhattacharyya 我做了
  • /usr/share/nginx/html中有哪些文件?
  • @David docker 中的目录包含: 50x.html favicon.ico index.html main.js main.js.map polyfills-es5.js polyfills-es5.js.map polyfills.js polyfills。 js.map runtime.js runtime.js.map styles.js styles.js.map vendor.js vendor.js.map
  • 尝试启用 nginx 调试日志并检查日志文件以查看为什么会出现 404。它通常应该与 Ratnadeep 指定的 try_files 规则一起使用。

标签: angular docker nginx npm angular-cli


【解决方案1】:

尝试将其添加到您的 ngnix 配置文件中:

http {
    ... other configs
    location / {
        try_files $uri $uri/ index.html
    }
}

【讨论】:

  • 我不得不写两个斜线try_files $uri $uri/ /index.html
  • 这适用于我的项目:try_files $uri $uri/ /index.html?$query_string;
【解决方案2】:

试试这个解决方案,我认为应该可以,因为我也在使用 Nginx 和 Angular Dockerfile 必须是:

# The builder from node image
FROM node:alpine as builder

# build-time variables
RUN apk update && apk add --no-cache make git

# Move our files into directory name "app"
WORKDIR /yourworkdir
COPY /yourworkdir/package*.json /frontend/
RUN npm install
COPY ./yourworkdir /frontend/

RUN npm run build -- --output-path=./dist/out


FROM nginx:alpine

COPY nginx/default.conf /etc/nginx/nginx.conf
COPY --from=builder /frontend/dist/out/ /usr/share/nginx/html

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

对于 Nginx 配置

 worker_processes  1;

    events {
        worker_connections  1024;
    }

    http {
        include /etc/nginx/mime.types;
        client_max_body_size 100m;

        server {
            listen 80;
            charset utf-8;
            server_name  localhost;

            root   /usr/share/nginx/html;
            index  index.html index.htm;
            include /etc/nginx/mime.types;

            gzip on;
            gzip_types text/css text/javascript application/x-javascript application/json;

            # frontend
            location / {
                try_files $uri $uri/ /index.html;
            }
        }
    }

我认为如果你也放上你的 docker-compose 文件会更好。

【讨论】:

    【解决方案3】:

    在您的 Dockerfile 中公开一个端口:

    ### STAGE 1: Build ###
    FROM node:12.7-alpine AS build
    WORKDIR /usr/src/app
    COPY package.json ./
    RUN npm install
    COPY . .
    RUN npm run build
    
    ### STAGE 2: Run ###
    FROM nginx:1.17.1-alpine
    EXPOSE YOUR_PORT
    COPY --from=build /usr/src/app/dist/TBH-GUI /usr/share/nginx/html
    

    这是nginx的基本配置:

    server {
    
      listen YOUR_PORT;
      server_name YOUR_SERVER_NAME;
    
      location / {
        root /usr/share/nginx/html;
    
        index index.html index.htm;
    
        try_files $uri $uri/ /index.html;
      }
    }
    

    【讨论】:

    【解决方案4】:

    您的 ngnix.conf 应该如下所示:

    server {
            listen 0000; # port
            server_name <IP>; 
            index index.html;
    
            location /api/v1/ {
                proxy_pass http://127.0.0.1:8080; #rest api IP/URL and port
                proxy_http_version 1.1;
                proxy_set_header Connection "";
                proxy_set_header X-Real-IP     $proxy_add_x_forwarded_for;
            }
            location /{
                root "/usr/src/app/dist/TBH-GUI"; # path of angular application upto dist
                try_files $uri $uri/ /index.html;
            }
    
        }
    

    【讨论】:

      【解决方案5】:

      在您的 index.html 上,只需将 &lt;base href="/"&gt; 更改为 &lt;base href="./"&gt;

      【讨论】:

        【解决方案6】:

        这个错误是由于路由是虚拟的,实际上并不存在于服务器上。 一个简单的解决方法是使用哈希路由策略。

        在您的app.module.ts 中,找到RouterModule.forRoot(routes) 并将useHash 选项设置为true,如下所示:RouterModule.forRoot(routes, { useHash: true })

        更多详情请查看documentation

        【讨论】:

          猜你喜欢
          • 2019-12-28
          • 1970-01-01
          • 2021-12-27
          • 1970-01-01
          • 2020-10-21
          • 1970-01-01
          • 2022-08-02
          • 2022-12-17
          • 2015-02-20
          相关资源
          最近更新 更多