lor*_*ago 5 deployment nginx docker angular
我需要找到一种动态部署 Angular 应用程序的方法,以便同一个 docker 映像允许我进行多次部署(开发、暂存、生产),其中访问 URL 会被修改。
我正在使用 Angular-cli 6.4.1 在 Angular 7 中制作应用程序。对于部署,我创建了一个 docker 多级容器,在其中构建映像并使用 nginx 配置它。
问题是,对于部署,我们使用私有注册表,在其中使用处理重定向的代理,以便我的应用程序将按照以下方案部署:{SERVER_HOST} : {PORT} / {SERVER_LOCATION}
当我尝试访问该 URL 时,仅加载 index.html,因为其余资源与基本路径“/”相关联。
Angular 在构建中提供了一个参数(--base-href),允许修改整个应用程序的路径,但是它对我没有帮助,因为我需要相同的 Docker 映像来允许我执行不同的部署,以便 {SERVER_LOCATION } 参数并不总是相同。
我还尝试在运行时读取环境变量以修改基本标记的 href 属性,但是很难执行未加载到索引旁边的文件中的代码。
作为一种解决方法,我决定在索引中创建一个函数来执行 ajax 请求,该请求收集配置参数以加载其余资源,但我不喜欢它,因为它破坏了 Angular 的操作。
<-- This is working fine, but is not dynamic: -->
npm run build -- --prod --base-href https://myHost.net:8080/path/app/ --configuration=$configuration
<-- And this is working but is not Angular friendly -->
/** assets/data/appConfig.json */
{
"SERVER_HOST": "https://myHost.net:8080",
"SERVER_PATH": "/path/app/"
}
/** index.html */
<script>
(function() {
if (window.onerror) {
loadConfig();
}
function loadConfig() {
var xhttp = new XMLHttpRequest();
var url = 'assets/data/appConfig.json';
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.response);
window.appBaseHref = data.SERVER_PATH;
document.getElementById("base").href = data.SERVER_PATH;
}
};
xhttp.open('GET', url);
xhttp.send();
}
})()
</script>
Run Code Online (Sandbox Code Playgroud)
有人告诉我有一个选项可以跳过代理,但我找不到方法来做到这一点,我不知道如何配置它。我认为也许可以在 nginx 配置文件中进行某种调整,以便应用程序从提供的 URL 中“读取”,并且应用程序的基本 href 始终可以保留为“/”。
目前我的 nginx.conf 文件是:
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html =404;
}
location /documentation {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /documentation/index.html =404;
}
}
Run Code Online (Sandbox Code Playgroud)
其中位置路径“/”是我的角度应用程序,位置路径“/documentation”是项目文档的保留路径。
欢迎任何形式的帮助。
<--- 编辑 --->
这些天我一直在尝试几件事,事实是我很困惑如何继续,因为似乎没有任何效果。
我已经配置 Nginx 添加 env $uri+$basepath 属性,但我意识到关系恰恰相反。我需要我的index.html向代理路由而不是路径'/'发出请求,因为由于这个原因,请求甚至没有进入日志(代理不会重定向我,因为它没有我的前缀应用程序)
我给你举个例子: 我的应用程序托管在: myHost:8080/myapp/front 当我输入此 url(myHost:8080/myapp/front) 时,应用程序会加载索引,但关联的资源(样式、运行时、polyfills、scripts 和 main) 未加载,因为它们将请求发送到: myHost:8080/{resourcePath} 而不是 myHost:8080/myapp/front/{resourcePath}

此时我不知道该去哪里。我将能够得到我想要放置标志 --base-href /myapp/front 的结果,但我希望这条路线是动态的,并且取决于我的 VIRTUAL_HOST 系统的环境变量,这当然我不知道在构建应用程序时
接下来我粘贴我的 dockerfile 和 nginx 配置文件。
Dockerfile(注释行是未按预期方式工作的提案)。
### STAGE 0: Based on Node.js, to build and compile Angular ###
FROM node:alpine as node
# Create app directory
WORKDIR /app
# Copy the dependencies to install once and let Docker use the cache for the next builds
COPY package*.json /app/
# Install all dependencies
RUN npm install
# Copy all the project into the image
COPY ./ /app/
# Argument to build the image according to the environment
ARG configuration=production
# Compiles our project
RUN npm run build -- --prod --configuration=$configuration
### STAGE 1: Based on Nginx, to have only the compiled app, ready for production with Nginx ###
FROM nginx:1.13.3-alpine
## Remove default nginx website
RUN rm -rf /usr/share/nginx/html/*
## From 'builder' stage copy over the artifacts in dist folder to default nginx public folder
COPY --from=node /app/dist/dsa-frontend /usr/share/nginx/html
# Add directive
# COPY nginx-custom.conf.template /etc/nginx/conf.d/default.conf.template
COPY nginx-custom.conf /etc/nginx/conf.d/default.conf
# CMD /bin/bash -c "envsubst '\$VIRTUAL_SERVICE_LOCATION' < nginx-custom.conf > /etc/nginx/conf.d/default.conf"
CMD ["nginx", "-g", "daemon off;"]
Run Code Online (Sandbox Code Playgroud)
nginx-custom.conf
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /myapp/front$uri /myapp/front$uri/;
# try_files $uri $uri/ $uri$VIRTUAL_SERVICE_LOCATION $uri$VIRTUAL_SERVICE_LOCATION/ /index.html;
}
location /documentation {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /documentation/index.html =404;
}
}
Run Code Online (Sandbox Code Playgroud)
但这些似乎都不起作用。
最后,我们决定从代理中删除开发并打开一个新端口来部署此应用程序,因此根路径现在为“/”。
现在一切正常。
我想我设法获得了针对完全相同问题的全面(尽管可能相当脆弱- 请随意推荐改进!)解决方案:为多个环境重用一个 Angular/NGINX Docker 映像(因此有多个基本路由)。
此外,我想解决访问外部 API 的问题,因此应用程序请求的所有内容都将通过容器中的 NGINX,因此您不必考虑CORS。在我的例子中,我有两件事:
客户端路由按预期工作,ROOT_PATH对应于/.
我还没有尝试(但将要尝试):
最终结果如下所示:
在本地构建并运行容器(一旦一切就绪)
ROOT_PATH是您要查找的参数。
DNS_IP由于 NGINX 需要proxy_pass,您可能想用其他东西替代 Google DNS。
docker build . -t fancy-web-app && \
docker run -it --rm \
--name fancy-web-app-configured \
--publish target=80,published=80 \
--env ROOT_PATH='staging' \
--env WEBSOCKET_PATH='socket.io' \
--env IMAGE_PATH='image' \
--env API_URL='http://api.server.example.com/api/v1/' \
--env DNS_IP='8.8.8.8 8.8.4.4' \
fancy-web-app
Run Code Online (Sandbox Code Playgroud)
为了清楚起见,我将列出您需要的所有内容:
NGNIX
nginx.conf
在容器启动期间修改,否则无法使用,因为它引用了环境变量。
码头工人
docker-entrypoint.sh <-- * * * 这就是奇迹发生的地方。** **
Dockerfile
Multistage,作为运行时阶段的docker-entrypoint.sh默认入口点。
角
索引.html
使用默认的开发配置,在容器启动时修改,因此它变成“运行时配置”。
应用程序.conf.ts
配置允许您抽象出全局变量中的配置,并且不会将这种丑陋进一步带入您的服务中
应用程序模块.ts
角度依赖注入允许您在任何服务中引用配置
一些角度.service.ts
这是您使用注入配置的地方。
角度奖励积分
代理.conf.json
用于在没有容器的本地主机上工作(相当于用于开发的 nginx.conf,将由 WebPack/ 使用ng serve)
角度.json
在这里,您可以指定一次代理配置,然后默认将其放置在任何地方。
如果有兴趣,我可以设置 GitHub 存储库,其中包含所有需要的部分(请评论/评分,这样我就可以看到有必要)。
NGINX
1.nginx.conf
server {
listen 80;
# Serve static files (HTML, CSS, JS)
location /${ROOT_PATH} {
# Using `alias` insead of `root` directive, so ${ROOT_PATH}
# will be discarded and static file will be fetched straight
# from the specified folder
alias /usr/share/nginx/html;
try_files $uri $uri/ /index.html =404;
}
# Re-route calls to external APIs
location ~ ^/${ROOT_PATH}/(${WEBSOCKET_PATH}|${IMAGE_PATH})/(.*) {
resolver ${DNS_IP};
proxy_pass ${API_URL}/$1/$2$is_args$args;
proxy_http_version 1.1;
proxy_cache_bypass $http_upgrade;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
}
}
Run Code Online (Sandbox Code Playgroud)
码头工人
2. docker-entrypoint.sh
server {
listen 80;
# Serve static files (HTML, CSS, JS)
location /${ROOT_PATH} {
# Using `alias` insead of `root` directive, so ${ROOT_PATH}
# will be discarded and static file will be fetched straight
# from the specified folder
alias /usr/share/nginx/html;
try_files $uri $uri/ /index.html =404;
}
# Re-route calls to external APIs
location ~ ^/${ROOT_PATH}/(${WEBSOCKET_PATH}|${IMAGE_PATH})/(.*) {
resolver ${DNS_IP};
proxy_pass ${API_URL}/$1/$2$is_args$args;
proxy_http_version 1.1;
proxy_cache_bypass $http_upgrade;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
}
}
Run Code Online (Sandbox Code Playgroud)
3. Dockerfile
# Produce static files
FROM node:10.15.3-alpine
WORKDIR /app
COPY ./package.json ./package.json
COPY ./package-lock.json ./package-lock.json
RUN npm set progress=false && \
npm install --silent
COPY . /app
RUN npm run ng build -- --prod --output-path=dist
# Use NGINX to serve static files and re-route requests
FROM nginx:1.15.10-alpine
RUN rm -rf /usr/share/nginx/html/*
COPY --from=0 /app/dist/ /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf.template
COPY docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD [ "nginx", "-g", "daemon off;" ]
EXPOSE 80
Run Code Online (Sandbox Code Playgroud)
角
4.index.html
#!/usr/bin/env sh
set -eu
# Inject environment variables into NGINX configuration
# List all variables to be substituted to avoid clashing with
# NGINX own variables: https://serverfault.com/questions/577370
envsubst \
'${API_URL} \
${ROOT_PATH} \
${WEBSOCKET_PATH} \
${IMAGE_PATH} \
${DNS_IP}' \
< /etc/nginx/conf.d/default.conf.template \
> /etc/nginx/conf.d/default.conf
cat /etc/nginx/conf.d/default.conf
# Set correct HTML base tag, so static resources are fetched
# from the right path instead of the root path.
# NOTE: Trailing and leading slashes in base href are important!
# Using `~` separator to avoid problems with forward slashes
sed --in-place \
's~<base href="/">~<base href="/'$ROOT_PATH'/">~' \
/usr/share/nginx/html/index.html
# Set WebSocket API endpoint
# Using `~` separator to avoid problems with forward slashes
sed --in-place \
"s~webSocketPath.*,~webSocketPath: \`/$ROOT_PATH/$WEBSOCKET_PATH\`,~" \
/usr/share/nginx/html/index.html
# Set image API endpoint
# Using `~` separator to avoid problems with forward slashes
sed --in-place \
's~imageBaseUrl.*~imageBaseUrl: `${window.location}'$IMAGE_PATH'`~' \
/usr/share/nginx/html/index.html
cat /usr/share/nginx/html/index.html
exec "$@"
Run Code Online (Sandbox Code Playgroud)
5.app.conf.ts
# Produce static files
FROM node:10.15.3-alpine
WORKDIR /app
COPY ./package.json ./package.json
COPY ./package-lock.json ./package-lock.json
RUN npm set progress=false && \
npm install --silent
COPY . /app
RUN npm run ng build -- --prod --output-path=dist
# Use NGINX to serve static files and re-route requests
FROM nginx:1.15.10-alpine
RUN rm -rf /usr/share/nginx/html/*
COPY --from=0 /app/dist/ /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf.template
COPY docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD [ "nginx", "-g", "daemon off;" ]
EXPOSE 80
Run Code Online (Sandbox Code Playgroud)
6. app.module.ts(剪掉不感兴趣的细节)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fancy web app</title>
<base href="/">
<script>
// These default values make sense when you `npm start`
// They will be substituted during container startup
// Using global variable on the window object here.
// Is there a better way?
window['app-config'] = {
webSocketUrl: `${window.location.host}`,
webSocketPath: `/socket.io`,
imageBaseUrl: `${window.location}image`
};
console.log(window['app-config']);
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<pdd-root></pdd-root>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
7. some-angular.service.ts(剪掉不感兴趣的细节)
import { Injectable } from '@angular/core';
@Injectable()
export class Configuration {
webSocketUrl: string;
webSocketPath: string;
imageBaseUrl: string;
}
// Reading configuration out, so we have it Angular world
export const AppConfiguration: Configuration = window['app-config'];
Run Code Online (Sandbox Code Playgroud)
角度奖励积分
8. proxy.conf.json
{
"/socket.io/*": {
"target": "http://localhost:3000/socket.io/",
"ws": true,
"secure": false,
"logLevel": "debug",
"pathRewrite": { "^/socket.io" : "" }
},
"/image/*": {
"target": "http://localhost:3000/image/",
"secure": false,
"logLevel": "debug",
"pathRewrite": { "^/image" : "" }
}
}
Run Code Online (Sandbox Code Playgroud)
9. angular.json -> 请参阅下面的片段之前的最后一行
<--snip-->
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "fancy-web-app:build",
"proxyConfig": "proxy.conf.json"
<--snip-->
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3725 次 |
| 最近记录: |