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

RK3*_*RK3 4 angular-routing docker dockerfile angular angular7

我是 Angular 和 Docker 的新手。我开发了一个 Angular 7 应用程序并尝试对其进行 dockerize。我确实看过很多教程,并且能够构建 Docker 映像。下面是我的 Dockerfile

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;"]
Run Code Online (Sandbox Code Playgroud)

我使用命令运行 docker 容器

docker run -d --name containerName -p 8082:80 imagename
Run Code Online (Sandbox Code Playgroud)

我的容器确实启动了,在浏览器中查看http://IP-address:8082/ 后,我可以看到我的应用程序的 index html。除了我的应用程序的其他 url 像登录页面 ( http://IP-address:8082/login ) 或仪表板 ( 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;
    #}
}
Run Code Online (Sandbox Code Playgroud)

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

abd*_*ady 6

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

为避免这种情况,您需要 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 配置)中使用上面指定的命令替换该文件。

编辑

已经有图像可以做到这一点,因此您可以使用官方图像以外的图像,这是专门为此制作的,它应该可以正常工作:示例