繁体   English   中英

Dockerize Angular 与路由和 nginx

[英]Dockerize Angular with routing and nginx

我正在尝试 Dockerize 一个简单的具有路由的 Angular 9 应用程序。

我有以下内容:

Dockerfile

FROM nginx:alpine
RUN rm -rf /usr/share/nginx/html/*
COPY /dist /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]

我跑:

docker build --pull --rm -f "Dockerfile" -t ng-nexct-approval-ui-image:latest "."
docker run --rm -d  -p 4200:80/tcp --name ng-nexct-approval-ui-container ng-nexct-approval-ui-image:latest

当我访问:

http://localhost:4200/

我按预期得到了 nginx 页面。

如果我访问:

http://localhost:4200/nexct-approval-ui/index.html

我可以访问 /dist 目录中的 index.html 文件。

问题

如何访问 Angular 组件?

例如:

http://localhost:4200/login

http://localhost:4200/approval-edit/1573515

我得到一个404

问题

如何配置 docker 以便我可以访问以下 Angular 路由:

const routes: Routes = [
    { path:'login', component:LoginComponent, canActivate: [AuthGuard] },
    { path: 'approval-list', component: ApprovalListComponent, canActivate: [ApprovalListGuard] },
    { path: 'approval-edit/:tripId', component: ApprovalEditComponent, canActivate: [ApprovalEditGuard] }
];

更新

我将以下内容添加到Dockerfile

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

nginx.conf

server {
    listen   80;

    root /usr/share/nginx/html;
    index index.html;

    server_name _;

    location / {
        try_files  $uri /index.html
    }

}

我可以访问:

http://localhost:4200/nexct-approval-ui/index.html

(但这只是在ng build/dist文件夹中生成的空白 html 文件。

如果我尝试访问任何路线,我现在会得到500

2020/07/21 15:40:35 [error] 29#29: *24 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: 172.17.0.1, server: _, request: "GET /nexct-approval-ui/login HTTP/1.1", host: "localhost:4200"

172.17.0.1 - - [21/Jul/2020:15:40:35 +0000] "GET /nexct-approval-ui/login HTTP/1.1" 500 579 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36" "-"

当然,在 nginx 服务器上运行 Angular 应用程序是很常见的。 我正在努力在任何地方找到一个明确的答案。

This should make it return the index.html for any URL received, and therefore all the Angular router URIs should work even when going to the URL directly rather than being redirected from an internal section of the app.

server {
  listen 80;
  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }
}

另外,请确保您没有对 base_href 做任何疯狂的事情。

上次我这样做是在 Angular4 中,所以我可能已经过时了:)
希望这对你有用。


编辑以回答评论中的问题:
上面的 nginx.conf 将期望在/usr/share/nginx/html下找到index.html文件。 根据 ng 构建的执行方式,您需要将包含索引文件的文件夹的内容复制到根位置。 有时这是在 dist 下的嵌套文件夹中创建的。

当我复制 /dist 文件夹时,问题出在我的 Dockerfile 中。 所以我改变了:

COPY /dist /usr/share/nginx/html

COPY /dist/nexct-approval-ui /usr/share/nginx/html

现在它可以工作了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM