我们的测试工具项目,先是部署到linux环境,然后部署到k8s环境。尝试过几种写入环境变量的方法。
因为是python flask项目,本地开发调试的话,直接在启动配置项里写入环境变量,FLASK_ENV=dev
linux环境部署,项目是使用脚本启动的方式部署的。在启动脚本中写入shell语句:
export FLASK_ENV=pro
代码中就可以读入FLASK_ENV变量了
ENV FLASK_ENV=pro
# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.8-slim
EXPOSE 80
# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1
ENV FLASK_ENV=pro
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
ARG PIP_CACHE_DIR
# Install pip requirements
COPY requirements.txt .
RUN python -m pip install -r requirements.txt
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
WORKDIR /root
COPY . /root
# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["gunicorn", "--config", "/root/gunicornConfig.py", "manage:mytestsystem"]
dockerfile文件中设置的环境变量,无法区分k8s-测试环境和k8s-线上环境,都会设置为统一的环境变量。
apiVersion: apps/v1
kind: Deployment
metadata:
name: xxx-node
spec:
replicas: 1
selector:
matchLabels:
tier: backend
template:
metadata:
labels:
app: web
tier: backend
spec:
hostAliases:
- ip: "xxxxxx"
hostnames:
- "xxxxxx"
containers:
- name: adautotest
image: xxx/xx/xxxx:{{imageTag}}
ports:
- containerPort: 80
env:
- name: FLASK_ENV
value: pro
最后的 env字段设置环境变量。
在yaml文件中设置环境变量,可以区分k8s测试,k8s线上环境,代码及脚本中只需要读取环境变量使用即可。