> For the complete documentation index, see [llms.txt](https://cifar.gitbook.io/note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cifar.gitbook.io/note/fu-wu/docker-zhi-shi.md).

# Docker 知识

## 作用

* windows的沙箱就是 Vmware 虚拟机&#x20;
* Linux 的沙箱就是 docker 虚拟环境        kvm可以装window
* python 的沙箱就是 conda 环境&#x20;

> 可见沙箱机制何等重要，我现在想装solidwork 但是要动注册表，这我太害怕了，上次动注册表电脑被迫重装了，现在又动？不存在的，我有沙箱，虚拟一个没问题的话，再在本机装。

【Python】[Python创建虚拟环境的三种方式](https://blog.csdn.net/ARPOSPF/article/details/113616988)

## docker

sudo gpasswd -a $USER docker  ==> [添加docker权限](https://blog.csdn.net/u014090429/article/details/117781540)   [添加 docker 用户组](http://c.biancheng.net/view/849.html)     -a  补加

&#x20;                                                newgrp docker                   #更新docker用户组

好用：sudo usermod -aG  docker  $USER&#x20;

使文件夹，同用户组所在其他成员也可以修改：sudo chmod 775 /path/to/folder

[Docker —— 从入门到实践](https://yeasy.gitbook.io/docker_practice/)

[Docker0网络详解](https://blog.csdn.net/chj_1224365967/article/details/109206131)

> docker0的地址：172.17.0.1 &#x20;
>
> 就是docker内访问宿主机的ip :apple:,  如样例比对的库，在本机，但代码在docker 内。链接宿主机db
>
> 如何让程序通过 读取 "host.docker.internal" ，指向: 172.17.0.1 , 修改  /etc/hosts里设置一下

> #### 链接宿主机数据库 host.docker.internal 问题
>
> ret = ivcpd.InitIndex("host.docker.internal", "29530", "host.docker.internal", "33060", "root", "Casia!0429")
>
> 需要修改 /etc/hosts ，
>
> ret = ivcpd.InitIndex("172.17.0.1", "29530", "172.17.0.1  ", "33060", "root", "Casia!0429")
>
> 不需要修改，直接写 172.17.0.1 &#x20;

### docker 命令

* Docker 镜像加速配置 [阿里](https://cr.console.aliyun.com/cn-beijing/instances/mirrors)
* docker常用命令
* self
  * dockerfile 的 docker build -t centos:7 .  注意：最后的点代表当前文件路径。
  * dockerfile 的 FROM 回 pull 成为本地 docker images 下的镜像。方便以后构建
* 系统类
  * docker images
  * docker ps  （运行中的容器）
  * docker ps -a （全部docker容器，方便 restart 已经停止的容器）
  * docker rmi  <镜像 ID>（删除镜像）
  * docker rm  <容器 ID>（删除容器）
* 使用类
  * docker run -it ubuntu --name test\_name /bin/bash  （  run  创建，后连接使用）
  * [开放端口](https://www.west.cn/docs/61845.html)  -p :   ( eg: -p 8088:80 )
  * docker exec   -it  243c32535da7 /bin/bash（不推荐 docker  attach ，由于exit 导致容器停止）
  * docker stop <容器 ID>
  * docker restart <容器 ID>
  * 拷贝本地文件到容器： docker cp 本地路径 容器长ID:容器路径
  * docker stats ：[动态显示 Docker容器 的资源消耗情况](https://haicoder.net/docker/docker-stats.html)
* 参数类

  -i: 交互式操作。

  -t: 终端。

  -d: 后台运行
* 日志

  [docker logs <容器 ID>](https://www.runoob.com/docker/docker-logs-command.html)
* 其他参数
  * \--link     [解决容器重启后ip地址会改变](https://developer.aliyun.com/article/55912)
  * [-- restart ](https://blog.csdn.net/REX1129/article/details/110115211)

#### nvidia-docker run -dit --gpus all --name=指定容器名 --shm-size 8G -p 指定映射端口号:22 -e LC\_ALL=en\_US.utf-8 -v /data/账户名:/workspace pytorch:1.8

> 容器内用 gpu 的需要添加 --gpus 参数。不然会出现 nvidia-smi 不显示问题。且gpu 不可用。
>
> -e   LANG="en\_US.UTF-8"    (加不加引号，有待实验)

* 其中：--name是容器名称，需自行定义
* \--shm-size是docker共享内存大小，不指定会影响pytorch下数据加载，num\_workers只能设为0才可正常运行；实测指定8G，num\_workers为16，batch\_size为256可以正常运行
* -p 为容易映射端口号，22端口的映射方便vs code连接远程调试，需自行指定
* -v 为目录映射，格式为：宿主机目录：容器目录，推荐直接映射/data/账户名目录到容器内

[VS Code远程连接服务器，调试python代码](https://cifar.gitbook.io/link-ed/)

### **远程连接容器**

> **vscode** 远程连接Ubuntu容器

```bash
docker pull ubuntu
docker run -itd --name ubuntu-dev -p 8888:22 ubuntu
docker exec -it ubuntu-dev bash
apt-get update
apt install -y vim openssh-server openssh-client
vi /etc/ssh/sshd_config (PermitRootLogin yes)
passwd (修改root密码)
service ssh restart
```

> **vscode** 远程连接CrentOS容器

```bash
docker pull centos
docker run -itd --name centos-dev -p 8888:22 centos
docker exec -it centos-dev bash
yum install -y vim openssh-server openssh-client
vi /etc/ssh/sshd_config (PermitRootLogin yes)
passwd (修改root密码)
ssh-keygen -q -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key -N ''
ssh-keygen -q -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N ''
ssh-keygen -t dsa -f /etc/ssh/ssh_host_ed25519_key -N ''
/usr/sbin/sshd -D &      //ssh 后台启动，ssh-keygen 必须生成才可以使用
```

### 常见问题

1、容器stop，然后restart 容器，出现ssh连接不上问题&#x20;

> 解决方案：去容器中，重新启动ssh服务，上述代码最后一个指令。&#x20;

2、docker 内部安装mongo db&#x20;

> sudo apt-get install mongodb （安装完成）&#x20;
>
> 启动MongoDB命令:sudo service mongodb start。（安装完成，不代表能用，还要启动对应服务!!!）&#x20;
>
> 关闭MongoDB命令:sudo service mongodb stop。

3、docker 中文目录乱码

临时修改 ：LANG=en\_US.UTF-8      &&    source /etc/profile     ( 或 export  LANG=en\_US.UTF-8 )

永久添加：（运行镜像时）docker run --name containerName  -e LANG=en\_US.UTF-8

4、docker 中约定了 -v 挂载的目录，新增目录 :tomato: 怎么办？

可以 mount 挂载到约定目录下。

但不可以  ln -s  软连接。docker 读取软链接识别到真实路径为宿主机路径，从而失败。

5、多台内网服务器，安装docker环境sdk。

&#x20;[**docker save :** 将指定镜像保存成 tar 归档文件。](https://www.runoob.com/docker/docker-save-command.html)( 下方笔记例子 )

> docker save ubuntu:load>/root/ubuntu.tar&#x20;
>
> docker load\<ubuntu.tar                                         注意两个代码箭头方向。

6、[docker run 内部脚本](https://hub.docker.com/_/python)

```
$ docker run -it --rm --name my-running-script -v "$PWD":/usr/src/myapp -w /usr/src/myapp python:3 python your-daemon-or-script.py
```

7、docker-proxy

[镜像通信](https://blog.csdn.net/m0_45406092/category_9582157_2.html)

[Docker 容器连接](https://www.runoob.com/docker/docker-container-connection.html)   查看docker 网络： docker network ls&#x20;

[网络信息内容器和ip](https://blog.csdn.net/wangyue23com/article/details/111172076) :    docker network inspect +  上条命令结果

> network\_mode: "bridge"   .默认的网络模式。如果没有指定网络驱动，默认会创建一个 bridge 类型的网络。桥接模式一般是用在应用是独立的情况，容器之间不需要互相通信。
>
> network\_mode: "host"       .host 网络模式，针对的也是应用是独立的情况，在 host 网络模式下，移除了宿主机与容器之间的网络隔离，容器直接使用宿主机的网络，这样就能在容器中访问宿主机网络。
>
> vmware 图：<img src="/files/ndbhDbVCqHOKw0ztqJKN" alt="" data-size="line">

8、--entrypoint=/bin/bash   ， 可以自行配置“开机自启” 一号进程bash脚本

9、docker GPU 支持

普通docker不支持gpu,  gpu是nvidia docker支持的

[Docker运行GPU环境](https://blog.csdn.net/qq_23985359/article/details/108102779)

[Setting up NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#id2)

10、docker update --restart=always      容器名称

### 其他：

* [查看linux版本](https://www.php.cn/linux-435827.html)    cat /etc/os-release
* &#x20;[添加用户1](https://blog.csdn.net/junmuzi/article/details/8567127)  [添加用户2](https://www.cnblogs.com/YiYA-blog/p/9630774.html)
* 添加root 用户： sudo passwd root
* docker 容器增加端口&#x20;
  * [教程1](https://www.cnblogs.com/shijf/p/10386193.html)&#x20;
  * [教程2](https://www.cnblogs.com/yangzp/p/13570665.html)&#x20;
  * [Docker提交运行时容器成为镜像](https://blog.csdn.net/wtyicy/article/details/104143348)

### ssh

服务器[安装 ssh](https://blog.csdn.net/future_ai/article/details/81701744)

* ssh 端口映射   （proxy工作原理）可以在本地链接服务器端口，运行服务器jupyter环境学习

  ssh -L8000:localhost:8888 jiarui\@192.168.3.228  (本地端口8000   远端端口8888)

  [教程](https://blog.fundebug.com/2017/04/24/ssh-port-forwarding/)

### **docker部署训练环境指南**

#### ***镜像说明***

各训练服务器上训练基础docker镜像已经完成，输入`docker images`即可看到 `rmzk/pytorch:1.8.1`，该镜像基于pytorch官方镜像构建。

* 系统为Ubuntu 18.04，包含cuda11.1【3090显卡计算能力sm86，cuda10.2最高支持sm70】
* 已安装常用包：vim，git，htop，tmux，screen，openssh-server等
* 镜像中已经安装miniconda，方便多python环境管理
* base环境下已安装训练环境：pytorch1.8.1，torchvision==0.9.1等
* apt、pip、conda均已更换为国内源

**附录**

* pytorch1.8.1 使用opencv会报错`ImportError: libGL.so.1: cannot open shared object file`，解决方法： apt install libgl1-mesa-glx     【Dockerfile 已修正】

### Dockerfile

```docker
FROM pytorch/pytorch:1.8.1-cuda11.1-cudnn8-runtime
# FROM pytorch/pytorch:1.8.1-cuda10.2-cudnn7-runtime # cuda10.2
# 设置中文支持
ENV LANG="C.UTF-8" LANGUAGE="C.UTF-8" LC_ALL="C.UTF-8"  TZ="Asia/Shanghai"

# apt使用阿里云源
# 安装git,pip使用清华源
RUN sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list \
    && sed -i s@/security.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list \
    && apt update  \
    && apt install -y software-properties-common \
    && apt install -y \
    openssh-server \
    vim \ 
    tmux \
    screen \
    libgl1-mesa-glx \
    wget \
    htop \
    && apt clean \
    && rm -rf /tmp/* /var/lib/apt/lists/* /var/tmp* \
    && conda init bash \
    && pip install --upgrade pip \
    && pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple \
    && pip install opencv-python \
    && echo "PermitRootLogin yes" >> /etc/ssh/sshd_config


WORKDIR /root/

COPY config.tar.gz /root/

RUN tar -zxvf config.tar.gz && rm -rf config.tar.gz

# ENTRYPOINT ["sh", "./monitor.sh","1"]
```

从上得出，命令行快速换源命令

```
sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list  && sed -i s@/security.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list   && apt update
```

config.tar.gz  ( conda的源修改，和tmux的配置文件 )  包含 【.condarc .tmux.conf 】

.condarc

```
channels:
  - defaults
show_channel_urls: true
default_channels:
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
custom_channels:
  conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  msys2: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  bioconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  menpo: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  pytorch-lts: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  simpleitk: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
```

.tmux.conf

```
# Send prefix 
set-option -g prefix C-a 
unbind-key C-a 
bind-key C-a send-prefix 
 
 
# Shift arrow to switch windows 
bind -n S-Left previous-window 
bind -n S-Right next-window 
 
# Mouse mode 2.1 version 
set -g mouse on

# before 2.1
# setw -g mouse-resize-pane on
# setw -g mouse-select-pane on
# setw -g mouse-select-window on
# setw -g mode-mouse on
 
# Set easier window split keys 
bind-key v split-window -h 
bind-key h split-window -v 
 
# Easy config reload 
bind-key r source-file ~/.tmux.conf \; display-message "tmux.conf reloaded"


```

### Docker Compose

#### [docker-compose升级到最新版本](https://qastack.cn/programming/49839028/how-to-upgrade-docker-compose-to-latest-version)

[菜鸟教程](https://www.runoob.com/docker/docker-compose.html)   [一些常用命令](https://cloud.tencent.com/developer/article/1499032)

使用 ：docker-compose.yml        docker编排文件

### yaml

[YAML 入门教程](https://www.runoob.com/w3cnote/yaml-intro.html)

> 对象键值对使用冒号结构表示 **key: value**，【 冒号后面要加一个空格】。

## K8S

[详解 Kubernetes 包管理工具 Helm](https://mp.weixin.qq.com/s/vZVCXCCqNSkGAcF9YVVf_A)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://cifar.gitbook.io/note/fu-wu/docker-zhi-shi.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
