在容器內(nèi)部無法獲取容器名稱時汁讼,如何操作?
當創(chuàng)建容器時,我們可以通過記錄容器名稱與ID到redis中号显。
在容器內(nèi)部,通過 cat /proc/self/cgroup 獲取容器ID躺酒。
應用場景
在容器內(nèi)部押蚤,想要獲取容器名稱,替換容器內(nèi)某些文件內(nèi)的字符串羹应, 代碼如下:
# -*-coding:utf-8-*-
import os
import redis
def alter(file, new_str, old_str="abc_123abc"):
"""
替換文件中的字符串
file:文件名
old_str:就字符串
new_str:新字符串
"""
file_data = ""
with open(file, "r") as f:
for line in f:
if old_str in line:
line = line.replace(old_str, new_str)
file_data += line
with open(file, "w") as f:
f.write(file_data)
def get_container_name():
db = redis.Redis(host="192.168.0.111", port=6380, decode_responses=False)
# start: in container, run next code -------------------------------------------------
cmd = "cat /proc/self/cgroup"
output = os.popen(cmd)
rests = output.readlines()
container_message= rests[-1]
if not container_message:
container_id = "abc"
else:
container_id = container_message.strip().split("docker-")[-1][:12]
# end. ----------------------------------------------------------------------------------
container_name = None
if container_id != "abc":
key_name = "nm_" + container_id
container_name = db.hget("container_msg", key_name)
if container_name:
container_name = container_name.decode("utf-8")
return container_name
def run():
nginx_conf = "/etc/nginx/nginx.conf"
galaxy_yml = "/galaxy-central/config/galaxy.yml"
container_name = get_container_name()
if container_name is not None:
alter(nginx_conf, container_name)
os.popen("nginx -s reload")
# os.popen("cp /galaxy-central/config/galaxy.yml.sample /galaxy-central/config/galaxy.yml")
alter(galaxy_yml, container_name)
print("Replacement string 'abc_123abc' succeeded")
else:
print("Replacement string 'abc_123abc' failed")
if __name__ == '__main__':
run()