Docker方便一鍵構建項目所需的運行環境:首先構建鏡像(Image)。然後鏡像實例化成爲容器(Container),構成項目的運行環境。最後Vscode連接容器,方便我們在本地進行開發。下面以一個簡單的例子介紹在win10中實現:Docker安裝、構建鏡像、創建容器、Vscode連接使用。
Docker安裝
首先進入官網安裝Docker軟件。安裝好打開可能會出現錯誤:
1、讓更新WSL:直接在cmd中輸入命令 WSL --update更新即可。
2、An unexpected error was encountered while executing a WSL command... 看:
https://zhuanlan.zhihu.com/p/633252579
修復以上錯誤之後一般就能進入Docker界面了。
創建鏡像
鏡像的創建通常在Dockerfile文件中寫成代碼的形式,以下舉例一個簡單的鏡像創建代碼:
# 使用官方 Ubuntu 鏡像進行初始化 FROM ubuntu:22.04 # 設置容器目前的工作目錄 WORKDIR /app # Let the python output directly show in the terminal without buffering it first. ENV PYTHONUNBUFFERED=1 # 更新包以及安裝必要的依賴 RUN apt-get update && apt-get install -y \ wget \ git \ bzip2 \ libglib2.0-0 \ libxext6 \ libsm6 \ libxrender1 \ make\ g++ RUN rm -rf /var/lib/apt/lists/* # 安裝最新版本miniconda RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \ && bash Miniconda3-latest-Linux-x86_64.sh -b -p /opt/conda \ && rm Miniconda3-latest-Linux-x86_64.sh ENV PATH /opt/conda/bin:$PATH # 使用conda創建一個新的python環境HelloDocker RUN conda create -n HelloDocker python=3.9.7 # 初始化bash shell從而 'conda activate' 可以馬上使用 RUN conda init bash # 激活conda環境 RUN echo "conda activate HelloDocker" >> ~/.bashrc ENV PATH /opt/conda/envs/HelloDocker/bin:$PATH # 複製本地當前目錄的 requirement.txt 文件到容器的app文件夾中 COPY requirements.txt /app # 設置pip的鏡像源爲清華源 RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple # 根據 requirement.txt 爲 python 安裝各種包 RUN /bin/bash -c "source ~/.bashrc && pip install --no-cache-dir -r requirements.txt"
然後在Dockerfile目錄下使用如下命令即可創建鏡像:
docker build -t hello-docker .
以上代碼創建了一個Ubuntu系統鏡像。除了系統鏡像之外,還可以只創建python環境鏡像,具體可以查詢ChatGPT。以上代碼需要去外國鏡像網站下載Ubuntu的鏡像文件,可能很慢,因此可以在Docker軟件設置中修改鏡像源,在json中添加:
"registry-mirrors": [ "https://xxxxx.mirror.aliyuncs.com", "http://hub-mirror.c.163.com" ]
即修改爲清華源。
創建容器及Vscode連接
鏡像創建好之後,Vscode先安裝Docker插件,然後在需要使用容器運行的項目工作目錄下,創建目錄.devcontainer,並在該目錄下創建devcontainer.json文件,填寫容器創建配置:
{ "name": "HelloDocker Container", "image": "hello-docker", // 替換爲你構建的Docker鏡像名稱 "extensions": ["ms-python.python"], "settings": { "python.pythonPath": "/opt/conda/envs/HelloDocker/bin/python" } }
以上配置表示,使用我們前面已經創建的名爲hello-docker的鏡像創建名爲HelloDocker Container的容器。之後點擊VsCode右下角的綠色圖標"><",點擊“在容器中重新打開”。等待容器創建好之後,即可使用Vscode在相應的容器環境中進行開發了。