在ubuntu 20.04.1上使用docker的配置脚本(代理切换支持)


在ubuntu 20.04.1上使用docker的配置脚本(代理切换支持)

我在ubuntu 20.04.1上写了一篇名为在代理环境中使用docker的配置脚本的文章,但是我创建了一个可以切换到非代理环境的脚本。

脚本

https://gist.github.com/m-tmatma/7556d81a850a8145ded7074578722334

准备

  • 将其另存为setup-docker.py

  • 使用chmod +x setup-docker.py授予执行权限。

  • 如何使用

    帮助

    1
    2
    3
    4
    $ ./setup-docker.py
    usage:
    sudo ./setup-docker.py set http://proxy:port
    sudo ./setup-docker.py noproxy

    设置指定的代理

    设置为

    http://192.168.11.61:3128

    1
    sudo ./docker-proxy.py http://192.168.11.61:3128

    没有代理访问时

    1
    sudo ./docker-proxy.py noproxy

    如果您是一般用户并且想使用不带sudo的docker

    1
    2
    sudo usermod -a -G docker $USER
    sudo reboot

    脚本主体

    https://gist.github.com/m-tmatma/7556d81a850a8145ded7074578722334

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    #!/usr/bin/python3

    import string
    import subprocess
    import os
    import sys

    ###########################################################################
    #  template for /etc/apt/apt.conf
    ###########################################################################
    template_apt_conf = """\
    Acquire::http::Proxy "$http_proxy_url";
    Acquire::https::Proxy "$https_proxy_url";
    """


    ###########################################################################
    #  template for /etc/systemd/system/docker.service.d/override.conf
    ###########################################################################
    template_docker_service_override = """\
    [Service]
    Environment="HTTP_PROXY=$http_proxy_url"
    Environment="HTTPS_PROXY=$https_proxy_url"
    Environment="NO_PROXY=localhost,127.0.0.1"
    """

    ###########################################################################
    #  template for ~/.docker/config.json
    ###########################################################################
    template_config_json = """\
    {
      "proxies": {
        "default": {
          "httpProxy": "$http_proxy_url",
          "httpsProxy": "$https_proxy_url",
          "noProxy": "localhost,127.0.0.1"
        }
      }
    }
    """


    ###########################################################################
    #  write proxy data to a file
    ###########################################################################
    def write_proxy(file_name, input_template, http_proxy_url, https_proxy_url):
        if http_proxy_url or https_proxy_url:
            context = {
                'http_proxy_url' : http_proxy_url,
                'https_proxy_url' : https_proxy_url
            }
            template = string.Template(input_template)
            data = template.substitute(context)

            with open(file_name, "w") as fout:
                fout.write(data)
            print("wrote: " + file_name)
        else:
            if os.path.exists(file_name):
                os.unlink(file_name)
            print("removed: " + file_name)

    ###########################################################################
    #  get the home directory of the original user
    ###########################################################################
    def get_original_home():
        user = os.environ['SUDO_USER']
        if user:
            home_dir = os.path.expanduser('~' + user)
        else:
            home_dir = os.path.expanduser('~')
        return home_dir

    ###########################################################################
    #  write etc/apt/apt.conf
    ###########################################################################
    def write_apt_conf(http_proxy_url, https_proxy_url):
        write_proxy('/etc/apt/apt.conf', template_apt_conf, http_proxy_url, https_proxy_url)

    ###########################################################################
    #  write /etc/systemd/system/docker.service.d/override.conf
    ###########################################################################
    def write_docker_service_override(http_proxy_url, https_proxy_url):
        docker_service_d = '/etc/systemd/system/docker.service.d'
        if not os.path.isdir(docker_service_d):
            os.mkdir(docker_service_d)

        override_conf = os.path.join(docker_service_d, "override.conf")
        write_proxy(override_conf, template_docker_service_override, http_proxy_url, https_proxy_url)

    ###########################################################################
    #  write ~/.docker/config.json
    ###########################################################################
    def write_docker_config(http_proxy_url, https_proxy_url):
        # get the path of ~/.docker
        home_dir = get_original_home()
        docker_dir = os.path.join(home_dir, ".docker")

        # create ~/.docker
        if not os.path.isdir(docker_dir):
            os.mkdir(docker_dir)

        # get ~/.docker/config.json
        config_json = os.path.join(docker_dir, "config.json")
        write_proxy(config_json, template_config_json, http_proxy_url, https_proxy_url)

    ###########################################################################
    #  usage
    ###########################################################################
    def usage():
        script = sys.argv[0]
        print("usage:")
        print("sudo " + script + " set http://proxy:port")
        print("sudo " + script + " noproxy")

    def exec(command):
        subprocess.call(command.split(), shell=False)
        print("ran: " + command)

    if __name__ == '__main__':
        if len(sys.argv) < 2 or os.getuid() != 0:
            usage()
            sys.exit(1)

        http_proxy_url = None
        https_proxy_url = None
        cmd = sys.argv[1]
        if cmd == "set":
            if len(sys.argv) == 3:
                http_proxy_url = sys.argv[2]
                https_proxy_url = sys.argv[2]
            else:
                usage()
                sys.exit(1)
        elif cmd == "noproxy":
            pass
        else:
            usage()
            sys.exit(1)

        exec('apt install -y docker.io docker-compose')

        write_apt_conf(http_proxy_url, https_proxy_url)
        write_docker_service_override(http_proxy_url, https_proxy_url)
        write_docker_config(http_proxy_url, https_proxy_url)

        exec('systemctl daemon-reload')
        exec('systemctl restart docker')