是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
。
为了避免这种情况,无论请求是什么,您都需要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/