This time I will show you how to deploy Angular containers and what are the precautions for Angular container deployment. The following is a practical case, let's take a look.
We know that Docker has two very important concepts: image and container. Anguar container deployment only needs to write the directory dist generated by the Angular-built production environment (for example: ng build -prod) to a static server image (for example: Nginx), and finally instantiate this image.
1. Build the Angular image
1. Compile Angular
Generally speaking, Angular building is also completed in a container. Create a Dockerfile.compile file in the root directory of the Angular project:
FROM node:8 LABEL authors="cipchk <cipchk>" WORKDIR /usr/src/app COPY package.json package.json RUN npm config set registry https://registry.npm.taobao.org \ && npm i COPY . . RUN ng build --prod</cipchk>
FROM specifies a node base image. This is the simplest way to build an Angular project. Basic
LABEL image metadata, such as authors author information
WORKDIR specifies the working directory within the image
COPY Copy the project package.json and install the dependent packages
RUN Copy the project file and execute the ng build command
Finally, execute the build Mirror command:
docker build -f Dockerfile.build -t ng-app-build .
where ng-app-build represents the mirror name.
2. Angular runtime environment
We will not build the Angularr runtime environment image based on compiling the Angular image, so it includes many meaningless files, such as npm i generated node_modules. Instead, extract the dist directory from the above image and generate a new image; the Angular runtime environment should be a clean and simple one.
Therefore, extract the dist from the compiled Angular image:
# 运行编译 Angular 镜像 docker run --name ng-app-build ng-app-build # 将 `dist` 复制到项目根目录下 docker cp ng-app-build:/usr/src/app/dist ./dist/ # 删除编译 Angular 镜像实例 docker rm -f ng-app-build
Note: The container path must be the WORKDIR path compiled by Angular in the previous step
Finally, create a Dockerfile in the root directory of the Angular project .package file:
FROM nginx COPY _nginx/default.conf /etc/nginx/conf.d/ RUN rm -rf /usr/share/nginx/html/* COPY /dist /usr/share/nginx/html CMD ["nginx", "-g", "daemon off;"]
The parameters are slightly the same as the previous section, except that the extracted dist is written to the Nginx default running directory in the image.
At the same time, use _nginx/default.conf of the Angular project as the Nginx configuration file, and include Nginx configuration in the project, such as when using HTML5 routing strategy, you need to deal with 404 issues, GZip, etc.
But I prefer that the Nginx configuration here should be extremely simple, and some GZip and SSL should be unified on the reverse proxy layer. After all, it is impossible to deploy only one application on a machine after containerization. .
The following is the most simplified configuration information of an Angular application:
server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
try_files can ensure that when the accessed path does not find the file, the index.html file will be used directly instead. This is the Angular HTML5 routing strategy A very important part.
Finally, build the production environment image:
docker build -f Dockerfile -t ng-app .
Of course, the compiled Angular image at this time has no meaning.
docker rmi -f ng-app-build
2. Run Angular
We can view the existing mirror:
docker images
Of course, the above is configured in Nginx A port 80 is used, so it can be used directly:
docker run -d -p 80:80 \ --name web \ ng-app
If your domain name is bound to the host, you can access it directly. So far, everything has been covered after Angular containerization. The following is the part about Nginx reverse proxy Docker application. If you have already done this, just ignore the next chapter.
Nginx reverse proxy
In most cases, a proxy server container will be used to forward multiple sites, so it is rarely directly in an Angular site Use port 80 directly, but forward it through another proxy layer.
I tried to use the jwilder/nginx-proxy mirror before. It was really convenient, but it gave me a lot of trouble in the SSL link. I finally gave up and switched to installing Nginx directly on the host. Acts as a reverse proxy.
During the Angular containerization process, we did not configure any SSL, GZip, etc., but only retained the configuration items required by the Nginx service, and we can complete this part in the reverse proxy layer.
This process includes three steps: install Nginx, install acme.sh to issue the Let's Sencrypt certificate, configure and run Nginx.
1. Install Nginx
Take CenOS7 as an example. For more systems, please Google:
sudo yum install epel-release sudo yum install nginx # 启动Nginx sudo systemctl start nginx
2. Through acme.sh Issue certificate
acme.sh 是国内一大牛写的用于简化申请 Let's Sencrypt 证书,并自动续签证书,几乎上第一次安装完全后,后续都无须人工干预。
Let's Sencrypt 不久前发布支持泛域,因此这一次也是申请了 *.ng-alain.com 泛域证书。
安装 acem.sh:
curl https://get.acme.sh | sh
这里我使用DNS来签发证书,目前支持几十种服务商,当然包括阿里云:
export Ali_Key="aaaaaaaaaaa" export Ali_Secret="xxxxxxxxxxxxxxxx" acme.sh --issue --dns dns_ali -d ng-alain.com -d *.ng-alain.com
Ali_Key 和 Ali_Secret 是对应的阿里云的 Access key,注意要给予 DNS 授权。
最后,利用 --installcert 来提取 Nginx 所需要的证书文件。
acme.sh --installcert \ -d ng-alain.com \ --key-file $(pwd)/proxy/certs/ng-alain.com.key \ --fullchain-file $(pwd)/proxy/certs/fullchain.cer \ --reloadcmd "service nginx force-reload"
acme.sh 会纪录这行命令的所有细节,并且当自动续签触发后再一次执行它们。其中 service nginx force-reload 是指命令执行完成后重启 nginx 使启证书立刻生效。
整个过程我非常顺利,没有任何错误,acme.sh 也有很多说明文档,包括中文,有关更多细节请自行阅读。
3、运行 Nginx
之前在安装 Nginx 时我们就已经启动了,那么,我们只需要对 /etc/nginx/nginx.conf 编写一些 Nginx 配置即可。
有两个主要细节:SSL配置和代理转化Angular容器实例端口的配置。
对于前者,若你在运行上述命令时依然保持路径的话,则:
ssl_certificate /root/proxy/certs/fullchain.cer; ssl_certificate_key /root/proxy/certs/ng-alain.com.key; ssl_session_timeout 30m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS; ssl_session_cache shared:SSL:10m; ssl_prefer_server_ciphers on;
而对于代理转化,这其决于你映射Angular容器的端口,例如上述在运行容器的命令是这样:
docker run -d -p 80:80 \ --name web \ ng-app
我们可以重新换另一个映射端口,例如:8001。
docker kill web docker run -d -p 8001:80 \ --name web \ ng-app
然后在 Nginx 配置相应的代理转化:
server { listen 80; server_name ng-alain.com www.ng-alain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name ng-alain.com www.ng-alain.com; location / { proxy_pass http://127.0.0.1:8001/; } }
server 这里有两个分别对 80 和 443,前者强制跳转 https,当你不希望用户使用 http 访问你站点时。
server_name 指定监听的域名
proxy_pass 指定代理转发域,8001 端口就是上述 Angular 应用所处容器所映射的端口
配置文件保持后,你可以先执行 nginx -t 来校验配置文件是否正确。
最后,重启 Nginx。
service nginx force-reload
三、持续部署
上述有系列的 Docker 命令甚是繁琐,应该把这一切自动化,有个专业名称叫:持续部署(简称:cd);ng-alain.com 现在是使用DaoCloud 完成这项工作。
DaoCloud 提供一种叫【安全镜像】的构建功能,分为三个步骤——编译、提取、打包;等同上述 Angular 项目的编译、提供和发布。
只需要在项目下创建 daocloud.yml;它是 DaoCloud 提供的一种自定义项目流程的定义文件,若你对上述已经了解,再来看它就不会非常陌生。以下是 ng-alain.com 完整的 daocloud.yml 内容:
version: 3 stages: - compile - deploy release: stage: compile job_type: lite_image_build only: branches: - master allow_failure: false compile: build_dir: / cache: false dockerfile_path: /Dockerfile.compile extract: - /usr/src/app/dist - /usr/src/app/_nginx/default.conf package: build_dir: / cache: false dockerfile_path: /Dockerfile.package self: stage: deploy job_type: DCS_deploy only: branches: - master allow_failure: false dependencies: - release app_name: web cluster_id: ""
注意: 其中 extract 务必包含完整路径。
四、总结
将生产环境容器化已经是一种架构标准,上述只是在部署ng-alain.com 的一些总结,实际可能遇到的问题会更多,大家可以通过以下找到答案:
Docker — 从入门到实践
Docker 问答录(100 问)
DaoCloud Services 文档
当然,未来Angular cli 也将会内置 Docker 部署,这里有一份来自 Angular 的相关ng docker 命令的设计文档。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to deploy Angular containers. For more information, please follow other related articles on the PHP Chinese website!

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version
Useful JavaScript development tools
