首页

通过 Docker 容器在 VS Code 中进行 Python 编程

你是否曾尝试与同事分享 Python 代码,却花费数小时调试”但在我的机器上可以运行”的问题?Docker 容器就像代码的集装箱——它们将 Python 环境、库和依赖项打包到一个密封的盒子中,在任何地方都能以相同方式运行。此外,你可以在 Docker Hub 上访问数以万计的预构建镜像,软件开发者在那里发布即用型环境,省去手动安装软件的麻烦。本教程将向你展示如何使用 VS Code 和 Docker Desktop 在隔离、可重现的环境中运行 Python。

核心概念

准备内容

步骤 1:安装 Docker Desktop

步骤 2:安装 Dev Containers 扩展

步骤 3:创建 Python 项目文件夹

步骤 4:创建 Dockerfile

# Choose the official Python slim image
FROM python:3.12-slim

# 1. Install system dependencies
RUN apt-get update && apt-get install -y \
    git curl build-essential && \
    rm -rf /var/lib/apt/lists/*

# 2. Install Python packages for data science and web apps
RUN pip install --no-cache-dir \
    pandas matplotlib seaborn streamlit jupyter

# 3. Install Node.js LTS from NodeSource
RUN curl -fsSL https://deb.nodesource.com/setup_lts.x | bash - \
    && apt-get install -y nodejs \
    && npm install -g npm@latest

# 4. Install Claude Code globally
RUN npm install -g @anthropic-ai/claude-code

# 5. Expose Streamlit port
EXPOSE 8501

步骤 5:创建 Dev Container 配置

{
  "name": "Python in Docker",
  "build": {
    "dockerfile": "Dockerfile"
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "ms-python.python",
        "ms-python.debugpy"
      ]
    }
  },
  "forwardPorts": [8501],
  "postCreateCommand": "python3 --version"
}

步骤 6:创建 Python 数据分析脚本

# Simple data analysis using the iris dataset
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

# Load the iris dataset
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = iris.target

# Display first few rows
print(df.head())

# Summary statistics
print("\nSummary statistics:")
print(df.describe())

# Create histograms
plt.figure(figsize=(10, 6))
plt.hist(df['sepal length (cm)'], bins=20, alpha=0.7, label='Sepal Length')
plt.hist(df['sepal width (cm)'], bins=20, alpha=0.7, label='Sepal Width')
plt.xlabel('Measurement (cm)')
plt.ylabel('Frequency')
plt.title('Iris Sepal Measurements')
plt.legend()
plt.show()

步骤 7:创建 Streamlit Web 应用

import streamlit as st
import numpy as np
import matplotlib.pyplot as plt

st.title("Old Faithful Geyser Data")

# Slider for number of bins
bins = st.slider("Number of bins:", min_value=5, max_value=50, value=30)

# Generate sample data (simulating Old Faithful eruption durations)
np.random.seed(42)
data = np.concatenate([
    np.random.normal(2, 0.5, 100),
    np.random.normal(4.5, 0.5, 150)
])

# Create histogram
fig, ax = plt.subplots()
ax.hist(data, bins=bins, edgecolor='black')
ax.set_xlabel('Eruption Duration (minutes)')
ax.set_ylabel('Frequency')
ax.set_title(f'Histogram with {bins} bins')

st.pyplot(fig)

步骤 8:在容器中重新打开

步骤 9:了解容器环境

现在你正在 Linux 容器内编写代码。让我们探索这意味着什么。

pwd

你将看到 /workspaces/python-docker-demo - 这是容器内的项目文件夹。

ls

你将看到创建的文件夹:.devcontainer/python/ 等。

cd ..
ls

你只会看到 python-docker-demo/ - 容器是隔离的。无法访问计算机的其他文件夹、桌面或文档。这种隔离确保 Python 环境干净且可重现。

cd python-docker-demo

步骤 10:逐行运行 Python 代码

容器已预装 Python 和数据科学包。让我们运行分析脚本。

步骤 11:运行 Streamlit 应用

该项目包含演示 Streamlit 应用,用于创建交互式直方图。

cd python
streamlit run app.py

步骤 12:进行简单更改

让我们修改应用以了解开发是如何工作的。

st.title("My First Python Docker App")

步骤 13:了解 Dockerfile(可选)

关键部分:

可使用的其他 Python 镜像:

更改基础镜像后,重新构建容器以应用更改。

步骤 14:在 Docker 镜像中安装 Python 包(可选)

通过终端中的 pip 安装的包(pip install package)是临时的,重新构建容器时会消失。要使包永久化,请将它们添加到 Dockerfile。

RUN pip install --no-cache-dir \
    pandas matplotlib seaborn streamlit jupyter scikit-learn
import sklearn
print(sklearn.__version__)

如果显示版本号且没有错误,则包已永久安装。

下一步

故障排除

工作流程概述

此设置为你提供专业的 Python 开发环境:

日常工作流程

设置完成后,这是日常例程:

  1. 启动 Docker Desktop - 打开应用并等待绿色状态指示器(Docker 必须运行)
  2. 打开 VS Code - 启动 VS Code 并打开项目文件夹
  3. 在容器中重新打开 - 如果尚未在容器中,点击绿色图标(左下角)并选择 Reopen in Container
  4. 编写和运行代码 - 编辑 .py 文件,使用 Shift+Enter 逐行运行,或使用 streamlit run app.py 运行应用
  5. 保存工作 - 代码文件(.py.ipynb)保存到计算机,并在会话之间持久存在
  6. 提交并推送 - 使用 GitHub Desktop 提交更改并推送到存储库

Steven Ge 创建于 2025 年 12 月 7 日。