2023年9月7日星期四

docker小心得

docker小心得

docker小心得

brief

这篇笔记将从容器写到镜像然后以alpine这一linux发行版为例介绍如何运行一个网络服务后端。

所以请先确保你的运行环境中已经安装好docker

reference

https://www.runoob.com/docker

在Alpine容器中安装配置ssh服务端-阿里云开发者社区 (aliyun.com)

Docker 架构

Docker 架构 | 菜鸟教程 (runoob.com)

容器

如果还没有镜像,而想从0嗯造一个容器:

  1. 首先你需要获取一个镜像
    docker pull

    例如,docker pull ubuntu获取一个ubuntu镜像。

    在后文将介绍一种通过 Dockerfile创建镜像的方法

  2. 接着就可以 容器,启动!了

    docker run [OPTIONS] IMAGE [COMMAND] [ARGs..]

这里的run command的参数比较常用的可能有

-d, --detach Run container in background and
print container ID

-h, --hostname string Container host name

-i, --interactive Keep STDIN open even if not attached
–ip string IPv4 address (e.g., 172.30.100.104)

-m, --memory bytes Memory limit

–name string Assign a name to the container

–pid string PID namespace to use

-p, --publish list Publish a container’s port(s) to the host

-t, --tty Allocate a pseudo-TTY

如果你在启动容器时开启了终端,可以在shell中执行 exit来退出exit,

如果只是退出终端而不是exit,可以 Ctrl+P+Q

查看所有容器

docker ps [options]

docker container ls, docker container list, docker container ps, docker ps

Options:
-a, --all Show all containers (default shows just running)
-f, --filter filter Filter output based on conditions provided
–format string Format output using a custom template:
‘table’: Print output in table format
with column headers (default)
‘table TEMPLATE’: Print output in table format
using the given Go template
‘json’: Print in JSON format
‘TEMPLATE’: Print output using the given
Go template.
Refer to https://docs.docker.com/go/formatting/
for more information about formatting output with
templates
-n, --last int Show n last created containers (includes all
states) (default -1)
-l, --latest Show the latest created container (includes all
states)
–no-trunc Don’t truncate output
-q, --quiet Only display container IDs
-s, --size Display total file sizes

例如cmd执行 docker ps -a

此时会显示所有runing、exit各种状态的容器

start和stop

docker start

docker stop

docker restart

进入容器

docker attach

Usage: docker attach [OPTIONS] CONTAINER

Attach local standard input, output, and error streams to a running container

Options:
–detach-keys string Override the key sequence for detaching a
container
–no-stdin Do not attach STDIN
–sig-proxy Proxy all received signals to the process
(default true)

docker exec

Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG…]

Execute a command in a running container

Options:
-d, --detach Detached mode: run command in the background
–detach-keys string Override the key sequence for detaching a
container
-e, --env list Set environment variables
–env-file list Read in a file of environment variables
-i, --interactive Keep STDIN open even if not attached
–privileged Give extended privileges to the command
-t, --tty Allocate a pseudo-TTY
-u, --user string Username or UID (format:
“<name|uid>[:<group|gid>]”)
-w, --workdir string Working directory inside the container

导入和导出

如果要导出本地某个容器,可以使用 docker export 命令。

docker export 01d > d:/111alp.zip

导出容器 01d5fd4e8335 快照到本地文件 111alp.zip

删除容器

docker rm -f 1e560fca3906

镜像

当运行容器时,使用的镜像如果在本地中不存在,docker 就会自动从 docker 镜像仓库中下载,默认是从 Docker Hub 公共镜像源下载。

list images

docker images

REPOSITORY TAG IMAGE ID CREATED SIZE
vscb/testalp latest 458ebb382c42 13 hours ago 51.1MB
my_test_docker2 latest 0ea960f374e2 32 hours ago 1.01GB
my_test_docker1 latest 697dd37ccdcd 32 hours ago 5.58MB
redis latest 506734eb5e71 2 weeks ago 138MB
alpine latest 7e01a0d0a1dc 4 weeks ago 7.34MB

部分匹配(如用正则),请用grep 管道 xargs来实现

删除

docker rmi [image]

从镜像run一个容器

docker run -i -t --name my_new_alp vscb/testalp:latest /bin/sh
exit

C:\Users\scarletborder>docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7ade58b54471 vscb/testalp:latest “/bin/sh” 27 seconds ago Exited (0) 12 seconds ago my_new_alp

根据容器创建镜像

$ docker commit -m="has update" -a="runoob" e218edb10161 runoob/ubuntu:v2

Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container’s changes

Aliases:
docker container commit, docker commit

Options:
-a, --author string Author (e.g., “John Hannibal Smith
hannibal@a-team.com”)
-c, --change list Apply Dockerfile instruction to the created image
-m, --message string Commit message
-p, --pause Pause container during commit (default true)

用Dockerfile文件创建镜像

Dockerfile 是一个用来构建镜像的文本文件,文本内容包含了一条条构建镜像所需的指令和说明。

注意 :Dockerfile 的指令每执行一次都会在 docker 上新建一层。所以过多无意义的层,会造成镜像膨胀过大。以 &&符号连接命令,这样执行后,只会创建 1 层镜像。

FROM centos
RUN yum -y install wget \
    && wget -O redis.tar.gz "http://download.redis.io/releases/redis-5.0.3.tar.gz" \
    && tar -xvf redis.tar.gz

其他指令详解

Docker Dockerfile | 菜鸟教程 (runoob.com)

补充,如果想在镜像创建完成前修改某些文本文件?

可以使用linux中的sed命令,Linux sed 命令 | 菜鸟教程 (runoob.com)

比如现在就要在 main.py里的line2增加多行内容

var1 = 114
var1 += 514
print(var1)
/tmp # sed -i "2a\print(f'now {var1}')\\
> print(2333)" main.py
/tmp # cat main.py
var1 = 114
var1 = 114
var1 += 514
var1 += 514
print(f'now {var1}')
print(var1)
print(var1)

Usage: docker buildx build [OPTIONS] PATH | URL | -

Start a build

Example:$ docker build -t nginx:v3 .

下载,上传docker hub

pull

Usage: docker pull [OPTIONS] NAME[:TAG|@DIGEST]

Download an image from a registry

Aliases:
docker image pull, docker pull

Options:
-a, --all-tags Download all tagged images in the repository
–disable-content-trust Skip image verification (default true)
–platform string Set platform if server is multi-platform
capable
-q, --quiet Suppress verbose output

push

Usage: docker push [OPTIONS] NAME[:TAG]

Upload an image to a registry

Aliases:
docker image push, docker push

Options:
-a, --all-tags Push all tags of an image to the repository
–disable-content-trust Skip image signing (default true)
-q, --quiet Suppress verbose output

Example:PS C:\Users\scarletborder> docker push vscb/testalp:1.5

端口映射

首先重提一下 docker run [OPTIONS] IMAGE [COMMAND] [ARG...]中的两个参数

-p, --publish list Publish a container’s port(s) to the host
-P, --publish-all Publish all exposed ports to random ports

接着,默认情况下,新建容器的IP是 0.0.0.0

所以在容器中的一些程序的函数当要指定Host时注意设置IP参数(毕竟大部分函数IP的默认参数是 127.0.0.1

或者在 docker run时加参数 --IP 127.0.0.1

Example

# Dockerfile
FROM alpine:3.12
LABEL author="vscb"             \
    version="1.4"            \
    description="test alpine evolved"  

COPY main.py /home/main.py
COPY test.py /home/test.py
RUN apk add python3                 \
    && apk add py3-pip              \
    && pip install --upgrade pip    \
    && pip install "fastapi[all]"   
# /home/main.py
from fastapi import FastAPI,Body
from pydantic import BaseModel
import uvicorn

app = FastAPI()

@app.get("/info")
async def getInfo():
    return str("This is a example server host")

class Item(BaseModel):
    name:str = None
    status:bool = True

@app.post("/postItem/")
async def poItem(item:Item):
    return {"code":item.name}

if __name__ == '__main__':
    uvicorn.run('main:app',host="0.0.0.0",port=8000)
PS C:\Users\scarletborder> docker run -d -p 127.0.0.1:8882:8000 vscb/testalp:1.5 python3 /home/main.py
async def main3():
    async with aiohttp.ClientSession() as session:
        resp = await session.put(
            url=f"http://127.0.0.1:8882/items/123",
            headers=my_header,
            data=json.dumps(
                {
                    "name":"123"
                }
            ),
        )
        print(await resp.text())

输出 {“code”:“123”} 验证完成

docker获得自己的IP

Pod IPPodIP地址,即docker容器的IP地址,此为虚拟IP地址

command: ["/bin/sh", "-c", "export POD_IP=`hostname -i`]

补充点shell知识,

&& and ||

&&左边的命令(命令1)返回真(即返回0,成功被执行)后,&&右边的命令(命令2)才能够被执行;换句话说,“如果这个命令执行成功&&那么执行这个命令”。 
语法格式如下:
 
    command1 && command2 [&& command3 ...]
 
1 命令之间使用 && 连接,实现逻辑与的功能。
2 只有在 && 左边的命令返回真(命令返回值 $? == 0),&& 右边的命令才会被执行。
3 只要有一个命令返回假(命令返回值 $? == 1),后面的命令就不会被执行。

||则与&&相反。如果||左边的命令(命令1)未执行成功,那么就执行||右边的命令(命令2);或者换句话说,“如果这个命令执行失败了||那么就执行这个命令。
1 命令之间使用 || 连接,实现逻辑或的功能。
2 只有在 || 左边的命令返回假(命令返回值 $? == 1),|| 右边的命令才会被执行。这和 c 语言中的逻辑或语法功能相同,即实现短路逻辑或操作。
3 只要有一个命令返回真(命令返回值 $? == 0),后面的命令就不会被执行。
-----------------------------------
shell中&&||的使用方法
https://blog.51cto.com/151wqooo/1174066

shell special char

Shell 中的特殊字符 | 菜鸟教程 (runoob.com)

shell -c opt

shell 会将 -c 后的部分当做代码来使用。

export

Linux export 命令用于设置或显示环境变量。

export[-fnp][变量名称]=[变量设置值]

参数说明

  • -f  代表[变量名称]中为函数名称。
  • -n  删除指定的变量。变量实际上并未删除,只是不会输出到后续指令的执行环境中。
  • -p  列出所有的shell赋予程序的环境变量。

network 下采用 DNS resolver

Compose 是用于定义和运行多容器 Docker 应用程序的工具。通过 Compose,您可以使用 YML 文件来配置应用程序需要的所有服务。然后,使用一个命令,就可以从 YML 文件配置中创建并启动所有服务。

Docker Compose

Overview of docker compose CLI | Docker Docs

https://yeasy.gitbook.io/docker_practice/compose/introduction

0 评论:

发表评论