这几节我们都是使用microk8s学习kubernetes,于是镜像库我们也是使用它的插件——registry。

开启镜像库插件

microk8s enable registry

模拟开发环境

我们使用Python作为开发语言来进行本系列的演练。

安装Python

sudo apt install python3.11

安装Pip3

pip3用于安装一些python工具。

sudo apt install python3-pip

安装virtualenv

为了让不同的项目有不同的依赖,我们使用virtualenv进行环境管理。

pip3 install virtualenv

创建虚拟环境

python3 -m virtualenv .venv --python=python3.11

进入虚拟环境

source .venv/bin/activate

导出依赖

项目编写完后,可以通过下面指令将依赖导出到文件中。

pip freeze > requirements.txt

编写代码

下面的程序需要传入两个参数:

  • port:服务启动的端口号
  • version:服务的版本号
# main.py
from http.server import HTTPServer, BaseHTTPRequestHandler
import argparse
import socket
 
version = 0
 
def get_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
        return ip

class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        data = "This service's version is {0}\n\nIP is:{1}".format(version, get_ip())       
        self.wfile.write(data.encode())
 
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('-port', metavar='N', type=int, help='port of service', required=True)
    parser.add_argument('-version', metavar='N', type=int, help='version of service', required=True)
    args = parser.parse_args()
    version = args.version
    host = ('0.0.0.0', args.port)
    server = HTTPServer(host, Resquest)
    print("Starting server, listen at: {0}:{1}".format(get_ip(), args.port))
    server.serve_forever()

镜像

编写Dockerfile

在上述代码文件(main.py)的同级目录,我们创建名字是Dockerfile的文件,并填入下面内容

From python:3.11
RUN pip install --upgrade pip
COPY requirements.txt /requirements.txt
RUN pip install -r /requirements.txt
COPY main.py /main.py
WORKDIR /
CMD ["python","main.py","-port","8888","-version","1"]

From python:3.11:用于拉取包含Python3.11的基础镜像,我们的镜像是基于这个镜像进行的。
RUN pip install --upgrade pip:是用于更新pip。
COPY requirements.txt /requirements.txt:是将工程下的Python依赖库描述文件复制到镜像中。
RUN pip install -r /requirements.txt:是在镜像中安装项目的Python依赖库。
COPY main.py /main.py:将代码拷贝到镜像中。
WORKDIR /:用于设置当前路径是工作路径。
以上命令都是在镜像构建时执行的。
CMD [“python”,“main.py”,“-port”,“8888”,“-version”,“1”]:用于启动Python程序,开启服务。它是在镜像被加载到容器中后运行的,算是运行时态。

构建镜像

在Dockerfile所在的目录执行下面命令构建镜像

docker build -t simple_http:v1 .

Sending build context to Docker daemon 16.25MB
Step 1/6 : From python:3.11
—> 815c8c75dfc0
Step 2/6 : RUN pip install --upgrade pip
—> Running in 57e024ec10c4
Requirement already satisfied: pip in /usr/local/lib/python3.11/site-packages (22.3.1)
Collecting pip
Downloading pip-23.1.2-py3-none-any.whl (2.1 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 187.7 kB/s eta 0:00:00
Installing collected packages: pip
Attempting uninstall: pip
Found existing installation: pip 22.3.1
Uninstalling pip-22.3.1:
Successfully uninstalled pip-22.3.1
Successfully installed pip-23.1.2
WARNING: Running pip as the ‘root’ user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Removing intermediate container 57e024ec10c4
—> eb67eb01d842
Step 3/6 : COPY requirements.txt /requirements.txt
—> b5b1f735bf1b
Step 4/6 : RUN pip install -r /requirements.txt
—> Running in 36c14c15258c
WARNING: Running pip as the ‘root’ user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Removing intermediate container 36c14c15258c
—> 77840086fbe4
Step 5/6 : COPY main.py /main.py
—> 7447438c2be0
Step 6/6 : CMD [“python”,“main.py”,“-port”,“8888”,“-version”,“1”]
—> Running in 48a0c45c2992
Removing intermediate container 48a0c45c2992
—> b336b9f1adee
Successfully built b336b9f1adee
Successfully tagged simple_http:v1

查看docker镜像

可以通过下面命令,查看指定名称的镜像。

 docker images simple_http:v1

在这里插入图片描述

推送镜像

在推送之前,需要给docker的镜像打个tag。这步在推送到诸如Dockerhub等镜像库时,是不需要的。关于这块的解释,可以见(The reason to tag an image locally is that this guide is primarily focussed on developers who will be building their apps on the local system and testing the deployment workflow on local systems, so it doesn’t make sense for us to use a remote image from Dockerhub as an example.——https://master–affectionate-northcutt-34a625.netlify.app/02_01_local_registry

docker tag b336b9f1adee localhost:32000/simple_http:v1

然后推送

docker push localhost:32000/simple_http:v1

在这里插入图片描述

参考资料

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐