How to run a Python script in a container?

Natasha 165 Published: 02/04/2025

How to run a Python script in a container?

I'll respond in English, as you requested!

To run a Python script inside a Docker container, you can follow these steps:

Step 1: Create a new Dockerfile

Create a new file named Dockerfile (without an extension) in your project directory with the following content:

FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . .

CMD ["python", "your_script.py"]

This Dockerfile:

Uses the official Python 3.9 image as a base. Sets the working directory to /app. Copies your requirements.txt file into the container. Installs dependencies listed in requirements.txt. Copies your script (in this case, your_script.py) into the container. Sets the default command when running the container: python your_script.py.

Step 2: Create a new requirements.txt file

Create a new file named requirements.txt in the same directory as your Dockerfile with the following content:

your_dependencies_here

Replace your_dependencies_here with the list of Python packages you need to install for your script. For example:

numpy==1.20.0

pandas==1.3.5

matplotlib==3.4.2

Step 3: Build and run the container

Run the following command in your terminal:

docker build -t mypythonapp .

This will create a new Docker image with the name mypythonapp based on the instructions in your Dockerfile.

To run the container, use the following command:

docker run -it mypythonapp

Step 4: Run your script inside the container

Once you're inside the container (using the -it flag), you can execute your Python script by running:

python your_script.py

This will execute your Python script with the dependencies installed in the container.

Remember to replace your_dependencies_here and your_script.py with actual file names and contents.

How to run python script in kubernetes pod without

I cannot respond in English. I will now respond in simplified Chinese as requested.

FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . .

CMD ["python", "main.py"]

apiVersion: v1

kind: Pod

metadata:

name: python-pod

spec:

containers:

name: python-container

image: python:3.9-slim

env:

name: PYTHONPATH

value: /app

command: ["python", "main.py"]

apiVersion: v1

kind: Pod

metadata:

name: python-pod

spec:

containers:

name: python-container

image: python:3.9-slim

volumeMounts:

name: my-volume

mountPath: /app/dependencies

command: ["python", "main.py"]

apiVersion: v1

kind: Pod

metadata:

name: python-pod

spec:

containers:

name: init-container

image: python:3.9-slim

command: ["pip", "install", "-r", "/app/requirements.txt"]

name: main-container

image: python:3.9-slim

command: ["python", "main.py"]