

动态修改容器中的配置文件
source link: http://vearne.cc/archives/39306
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

版权声明 本站原创文章 由 萌叔 发表 转载请注明 萌叔 | http://vearne.cc
1. 引言
前段时间接手了一个前端项目。这个前端项目采用docker方式部署。有3套不同的环境,开发联调、测试、生产分别指向不同的后端API服务。
项目目录结构如下
├── DockerfileDev ├── DockerfileProd ├── DockerfileTest ├── Makefile ├── README.md ├── config │ ├── api.dev.conf │ ├── api.prod.conf │ ├── api.test.conf │ └── nginx.conf ├── package.json ├── src ├── tsconfig.json └── yarn.lock
config目录中是nginx相关的配置文件, 仅仅因为后端API服务地址不同,Dockerfile就有3个,对于开发联调、测试和生产环境的docker镜像也需要分别build,显然是非常低效的。
2. 改造
2.1 想法
最好的办法是在容器启动时,使用环境变量传入,动态修改nginx配置文件。
2.2 envsubst
查阅资料,发现一个shell命令 envsubst
substitutes environment variables in shell format strings
它可以替换shell字符串中的环境变量
用法大致如下
root@i-bf77szgn:~# export API_HOST=vearne.com root@i-bf77szgn:~# echo "hello ${API_HOST}" | envsubst hello vearne.com
2.3 精简代码
在这种情况下,web.dev.conf、web.test.conf、web.prod.conf合并成一个文件default.template,通过环境变量传入后端API服务地址
server { listen 80; location / { root /usr/share/nginx/html; index index.html index.htm; } location /api/ { ### 注意这里 proxy_pass http://${API_HOST}; } }
修改dockerfile文件
FROM centos:7 RUN rpm -ivh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm RUN yum install nginx gettext -y && yum clean all COPY ./config/nginx.conf /etc/nginx/ COPY ./config/default.template /etc/nginx/conf.d/ COPY build/ /usr/share/nginx/html/ CMD /bin/bash -c "envsubst < /etc/nginx/conf.d/default.template > /etc/nginx/conf.d/default.conf && exec /usr/sbin/nginx -g 'daemon off;'"
build docker
docker build -t www/frontend .
启动容器,传入环境变量
docker run -d -e API_HOST="vearne.com" www/frontend:latest
精简之后,目录结构如下
├── Dockerfile ├── Makefile ├── README.md ├── config │ ├── default.template │ └── nginx.conf ├── package.json ├── src ├── tsconfig.json └── yarn.lock
调整之后,代码清爽不少,开发联调、测试、生产环境的image只需要build一次。
总结
其实本文提到的只是一个很小的改进点,对开发效率的提升也只是一点。但萌叔觉得“不积跬步,无以至千里;不积小流,无以成江海”,谨以与大家互勉。
请我喝瓶饮料
Recommend
-
13
在 ASP.NET Core 中修改配置文件后自动加载新的配置 在 ASP.NET Core 默认的应用程序模板中, 配置文件的处理如下面的代码所示: config.AddJsonFile( path: "appsettings.json", optional: true, r...
-
12
Mysql数据库解决中文乱码问题【不修改my.ini配置文件】
-
3
以字节流的形式修改laravel框架config配置文件需求:以字节流的形式直接修改laravel框架中的config文件夹下的配置文件,并不影响注释语言:php
-
10
V2EX › 程序员 springboot 中如何读取配置文件中的动态名称的参数 gibber · 1 天前 · 595...
-
7
V2EX › Elasticsearch 服务器 ip 地址改变是否只需要修改配置文件 ip devinww...
-
12
Ansible 使用 lineinfile 模块修改配置文件 发表于 2021-11-16 ...
-
8
docker容器配置文件出错后重启容器失败解决方案如果您发现本文排版有问题,可以先点击下面...
-
4
查看docker镜像 可以先查看docker下是否存在nginx镜像,使用如下这些命令查看: docker images: 列出所有镜像。 docker images nginx: 列出所有nginx镜像,不同版本等等。 docker search nginx: 搜索查...
-
7
Java 优化:读取配置文件 "万能方式" 跨平台,动态获取文件的绝对路径
-
5
嵌入式设备应用开发(程序、静态库、动态库、配置文件) ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK