gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:22:17 24 4
gpt4 key购买 nike

我是 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;"]

然后我使用命令运行 docker 容器

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

我的容器在浏览器中查看后确实启动了 http://IP-address:8082/我可以看到我的应用程序的索引 html。除此之外,我的应用程序的其他网址(如登录页面(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 发送请求时。

为避免这种情况,您需要 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

关于angular - Dockerizing Angular 应用程序后路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53838598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com