Dockerizing Angular应用后路由不起作用

RK3

是Angular和Docker的新手。我已经开发了一个Angular 7应用程序并尝试对其进行docker化。我确实看到了许多教程,并且能够构建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;"]

我使用命令运行docker容器

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

我的容器确实启动了,并且在浏览器中查看了http:// IP-address:8082 /之后,我可以看到我的应用程序的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;
    #}
}

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

阿卜杜拉卡迪

发生这种情况是因为基本nginx映像将尝试处理来自的请求docroot,因此login.html当您向发送请求时,它将尝试查找一个/login

为了避免这种情况,index.html 无论请求什么,您都需要nginx来提供服务,从而让您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配置)。

编辑

已经有可以完全做到这一点的图像,因此您可以使用除官方图像以外的其他图像(专用于此图像),它应该可以正常工作:示例

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章