Python Quick Start
This document describes the process of manually containerizing a Python application from the ground up and deploying it to CloudBase Cloud Run. The project uses flask as the application runtime framework and employs gunicorn as the WSGI server for the production environment.
Sample code:
https://github.com/TencentCloudBase/cloudbase-examples/tree/master/cloudbaserun/python
or deploy to cloud hosting with one click:
Project Structure
Project Structure
├── .dockerignore
├── Dockerfile
├── README.md
├── main.py
└── requirements.txt
.dockerignore: Used to specify files and directories to be excluded when building a Docker image. By using the.dockerignorefile, you can reduce the image size and build time.Dockerfile: is a text file that contains a series of instructions for defining how to build a Docker image. By writing a Dockerfile, you can automatically create an image that includes the application and its runtime environment, achieving environment consistency and rapid deployment.main.py: the startup file for the application service, implementing the business logic.requirements.txt: Lists the required Python packages and version information for the application, used to install dependencies when building the Docker image.
Step 1: Write a Basic Application
Create a new directory named helloworld-python and enter this directory:
mkdir helloworld-python
cd helloworld-python
Create a file named main.py and paste the following code into it:
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=80)
The above code will create a basic Web server and listen on port 80.
Step 2: Manage Project Dependencies
In the project root directory, create a file named requirements.txt and add the following content:
Flask==3.1.1
gunicorn==23.0.0
If you need other dependencies, add the corresponding packages and versions in the requirements.txt file.
Alternatively, you can use a Python virtual environment to manage project dependencies, ensuring that the project's dependencies do not conflict with other Python packages on the system:
Create a virtual environment
python -m venv env
source env/bin/activate # Activate the virtual environmentInstall dependencies and generate requirements.txt
pip install Flask gunicorn
pip freeze > requirements.txt
Using pip freeze to generate the requirements.txt file must be performed in a python virtual environment; otherwise, the generated requirements.txt will include all dependencies on the machine, which may cause deployment failure.
Step 3: Containerize the Application
Create a file named Dockerfile in the project root directory with the following content:
# Use the official Python lightweight image
# https://hub.docker.com/_/python
FROM python:3-alpine
# The container's default time zone is UTC. To use Shanghai time, enable the following time zone setting command.
# Set the time zone. The container's default time zone is UTC.
RUN apk add tzdata && \
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
echo Asia/Shanghai > /etc/timezone
ENV APP_HOME /app
WORKDIR $APP_HOME
# Copy local code to the container
COPY . .
# Set environment variables
ENV PYTHONUNBUFFERED=1
ENV GUNICORN_WORKERS=1
ENV GUNICORN_THREADS=4
ENV GUNICORN_TIMEOUT=60
# Install dependencies to the specified /install folder
# Use a domestic mirror source to improve download speed.
RUN pip config set global.index-url http://mirrors.cloud.tencent.com/pypi/simple && \
pip config set global.trusted-host mirrors.cloud.tencent.com && \
pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir -r requirements.txt
EXPOSE 80
# Start the Web Service
# If your container instance has multiple CPU cores, we recommend setting the number of threads equal to the number of CPU cores.
CMD exec gunicorn --bind :80 --workers ${GUNICORN_WORKERS} --threads ${GUNICORN_THREADS} --timeout ${GUNICORN_TIMEOUT} main:app
Add a .dockerignore file to exclude files from the container image:
Dockerfile
README.md
*.pyc
*.pyo
*.pyd
__pycache__
.pytest_cache
env/
Step 4 (Optional): Build and Run Locally
If you have Docker installed locally, you can run the following command to build the Docker image locally:
docker build -t helloworld-python .
After a successful build, run docker images to view the built image:
REPOSITORY TAG IMAGE ID CREATED SIZE
helloworld-python latest df1440c18b5c 8 seconds ago 75.9 MB
You can then upload this image to your image repository.
Run the following command to start the container:
docker run -p 80:80 helloworld-python
Access http://localhost, you should see the "Hello World!" output.
Step 5: Deploy to CloudBase Cloud Hosting
If you have installed CloudBase CLI, you can use the following command in the project directory to deploy the application to CloudBase Cloud Hosting:
tcb cloudrun deploy
After entering the environment and service names, the CLI will automatically package the application image and deploy it to Cloud Hosting. For more deployment methods, refer to Deploying Services.
Configuration Specifications
- Configuration is typically placed in the project directory or configured using environment variables
- During service deployment, specify the startup port for the service on cloud hosting.
- It is recommended to use environment variables to manage configurations across different environments
Best Practices
- Use a virtual environment to manage dependencies.
- Use a domestic mirror source to accelerate dependency installation
- Properly set the container time zone
- Use .dockerignore to exclude unnecessary files
- Use gunicorn as the WSGI server for production environments
You can refer to the following sample Python framework projects: