我的部署包括:
- 一个初始化容器
- 长期服务
- 需要配置相关服务的 sidecar。
一旦配置了单独的服务,sidecar 的工作就完成了。但是,它不能终止,因为 Kubernetes 只会重新启动它。它不应该是 init 容器的一部分,因为它不应该阻止服务运行。
由于部署不允许OnFailure
restartPolicy,我目前的实现是让sidecar在完成配置任务后进入睡眠状态。
有没有办法让容器在部署不重启的情况下终止?或者,有没有办法让 init 容器与常规容器一起运行?
解决 XY 问题的一些细节:
- 该服务进行一些处理并将结果转储到数据库中。
- 相关服务为存储在数据库中的值提供 API。
- 这两个服务在不同的部署中,因为我预计它们会单独扩展。
例子:
#my-service.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-service
spec:
replicas: 1
template:
spec:
initContainers:
- name: my-service-init
image: my-service
imagePullPolicy: IfNotPresent
env:
- name: DATABASE_URL
value: postgres://postgres:postgres_password@$db_host:5432/database
args: ['init_script.py']
containers:
- name: my-service
env:
- name: DATABASE_URL
value: postgres://db_role:db_password@$db_host:5432/database
image: my-service
imagePullPolicy: IfNotPresent
args: ['main.py']
- name: related-service-configure
env:
- name: RELATED_API_SERVICE_ADMIN_ENDPOINT
value: http://related_api_service/api/
image: my-service
imagePullPolicy: IfNotPresent
args: ['manage_related_service.py']
#related-api-service.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: related-api-service
spec:
replicas: 1
template:
spec:
containers:
- name: related-api-service
env:
- name: DATABASE_URL
value: postgres://db_role:db_password@$db_host:5432/database
image: related-api-image
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
name: http
protocol: TCP
#manage_related_service.py
import time
import requests
import json
def upgrade_metadata(query_url, metadata_file):
with open(metadata_file) as fp:
metadata = json.load(fp)
print(f"Querying {query_url}...")
rsp = requests.post(query_url, json=metadata)
response = rsp.json()
print(f"Response to request was:\n{response}")
if response.get('success') != 'True':
raise ValueError("Metadata upgrade was not successful")
if __name__ == '__main__':
from environs import Env
env = Env()
env.read_env()
RELATED_API_SERVICE_ADMIN_ENDPOINT = env("RELATED_API_SERVICE_ADMIN_ENDPOINT")
METADATA_FILE = env("METADATA_FILE", "metadata.json")
upgrade_metadata(RELATED_API_SERVICE_ADMIN_ENDPOINT, METADATA_FILE)
# Once metadata has been uploaded, sleep forever
while True:
time.sleep(3600)