Dockerizing Angular 应用程序后路由不起作用

Routing doesn't work after Dockerizing Angular app

我是 Angular 和 Docker 的新手。我开发了一个 Angular 7 应用程序并试图 dockerize 它。我确实看过很多教程并且能够构建 Docker 图像。 下面是我的Docker文件

FROM nginx:1.13.3-alpine
## Remove default nginx website
RUN rm -rf /usr/share/nginx/html/*
COPY ./ /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

并且我 运行 docker 容器使用命令

docker run -d --name containerName -p 8082:80 imagename

我的容器确实启动了,在浏览器中查看后 http://IP-address:8082/ I could see index html of my app. Apart from that none other url of my application like the login page (http://IP-address:8082/login) or dashboard (http://IP-address:8082/dashboard) 可以正常工作。我看到 404 页面未找到问题。还缺少什么来确保路由在我的 dockerized 容器中正常工作?

下面是我的default.conf文件

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

我的 docker 版本是 Docker 版本 17.03.2-ce。 任何帮助表示赞赏

发生这种情况是因为基础 nginx 图像将尝试为来自 docroot 的请求提供服务,因此当您向 [ 发送请求时它会尝试找到 login.html =13=].

为避免这种情况,无论请求如何,您都需要 nginx 为 index.html 提供服务,从而让 angular 负责路由。

为此,您需要更改当前图像中的 nginx.conf,以包含以下内容:

try_files $uri $uri/ /index.html;

而不是默认值:

try_files $uri $uri/ =404;

你可以通过多种方式做到这一点,但我想最好的方法是在你的 Dockerfile 中添加一个额外的命令,像这样复制 nginx 配置:

COPY nginx/default.conf /etc/nginx/conf.d/default.conf

并用上面指定的命令替换目录中的 nginx/default.conf 文件(包含默认的 nginx 配置)。

编辑

已经有图片可以做到这一点,所以您可以使用官方图片以外的图片,专门为此制作的图片应该可以正常工作:example