容器内部获取容器ID

在容器内部无法获取容器名称时,如何操作?
当创建容器时,我们可以通过记录容器名称与ID到redis中。
在容器内部,通过 cat /proc/self/cgroup 获取容器ID。

应用场景

在容器内部,想要获取容器名称,替换容器内某些文件内的字符串, 代码如下:


# -*-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()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,808评论 0 10
  • 人生匆匆而来, 匆匆而过, 情为何物, 情在何方? 苟且偷安的人生, 快餐而过的生活, 情是随风, 情在桌上, 生...
    多果加阅读 253评论 0 0
  • 会唱歌的白开水 文/孙海燕 “咕噜,咕噜……” 白开水在透明的养生壶里挤着推着,跳着闹着,欢快地唱着歌。 春来了。...
    雲水禅心211阅读 444评论 0 3
  • 图片发自简书App 乡村路硬化以后,进出 “郭岔大院”的路平坦便利了太多,但一场又一场的大雪覆盖,给进出带来...
    冯建民_3f37阅读 1,746评论 0 8