31

动态修改容器中的配置文件

 5 years ago
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.
neoserver,ios ssh client
版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | 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一次。

总结

其实本文提到的只是一个很小的改进点,对开发效率的提升也只是一点。但萌叔觉得“不积跬步,无以至千里;不积小流,无以成江海”,谨以与大家互勉。

请我喝瓶饮料

ZzaQjmz.jpg!web


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK