Home

Python Coding in VS Code via Docker Container

Ever tried to share your Python code with a colleague, only to spend hours debugging “but it works on my machine” issues? Docker containers are like shipping containers for code—they package your Python environment, libraries, and dependencies into a sealed box that works the same everywhere. Plus, you get access to tens of thousands of pre-built images on Docker Hub, where software developers publish ready-to-use environments, skipping the pain of manual software installation. This tutorial shows you how to run Python in an isolated, reproducible environment using VS Code and Docker Desktop.

Key Concepts

What You’ll Need

Step 1: Install Docker Desktop

Step 2: Install Dev Containers Extension

Step 3: Create a Python Project Folder

Step 4: Create the 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

Step 5: Create the Dev Container Configuration

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

Step 6: Create a Python Data Analysis Script

# 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()

Step 7: Create a Streamlit Web App

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)

Step 8: Reopen in Container

Step 9: Understand the Container Environment

Now you’re coding inside a Linux container. Let’s explore what this means.

pwd

You’ll see /workspaces/python-docker-demo - this is your project folder inside the container.

ls

You’ll see the folders you created: .devcontainer/, python/, etc.

cd ..
ls

You’ll only see python-docker-demo/ - the container is isolated. You can’t access your computer’s other folders, Desktop, or Documents. This isolation ensures your Python environment is clean and reproducible.

cd python-docker-demo

Step 10: Run Python Code Line by Line

The container has Python pre-installed with data science packages. Let’s run the analysis script.

Step 11: Run the Streamlit App

The project includes a demo Streamlit app that creates an interactive histogram.

cd python
streamlit run app.py

Step 12: Make a Simple Change

Let’s modify the app to see how development works.

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

Step 13: Understanding the Dockerfile (Optional)

Key parts:

Other Python images you can use:

After changing the base image, rebuild the container to apply changes.

Step 14: Install Python Packages in the Docker Image (Optional)

Packages installed via pip in the terminal (pip install package) are temporary and disappear when you rebuild the container. To make packages permanent, add them to the Dockerfile.

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

If it displays the version without errors, the package is installed permanently.

Next Steps

Troubleshooting

Workflow Overview

This setup gives you a professional Python development environment:

Everyday Workflow

Once everything is set up, here’s your daily routine:

  1. Start Docker Desktop - Open the app and wait for the green status indicator (Docker must be running)
  2. Open VS Code - Launch VS Code and open your project folder
  3. Reopen in Container - If not already in the container, click the green icon (bottom-left) and select Reopen in Container
  4. Write and run code - Edit .py files, run line-by-line with Shift+Enter, or run apps with streamlit run app.py
  5. Save your work - Your code files (.py, .ipynb) are saved to your computer and persist across sessions
  6. Commit and push - Use GitHub Desktop to commit your changes and push to the repository

Created by Steven Ge on December 7, 2025.