run python in docker
时间: 2023-10-19 21:31:20 浏览: 119
To run Python in Docker, you can follow these steps:
1. Create a Dockerfile: Start by creating a file named `Dockerfile` in your project directory.
2. Define the base image: In the Dockerfile, specify the base image you want to use. For example, you can use the official Python image from Docker Hub:
```
FROM python:3
```
3. Copy your code: Use the `COPY` instruction in the Dockerfile to copy your Python code into the container. Let's assume your code is in a file named `app.py`:
```
COPY app.py /app/app.py
```
4. Set the working directory: Use the `WORKDIR` instruction to set the working directory inside the container:
```
WORKDIR /app
```
5. Install dependencies: If your Python code has any dependencies, you need to install them in the container. You can do this by adding a `requirements.txt` file to your project and running `pip install` inside the Dockerfile:
```
COPY requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt
```
6. Specify the command to run: Finally, use the `CMD` instruction to define the command that should be executed when the container starts. In this case, we want to run the `app.py` file:
```
CMD ["python", "app.py"]
```
7. Build and run the Docker image: Open a terminal, navigate to your project directory, and run the following commands:
```
docker build -t my-python-app .
docker run my-python-app
```
This will build a Docker image based on your Dockerfile and then run a container using that image. The Python code in `app.py` should now be executed inside the Docker container.
阅读全文