Python Quick Start
This document introduces the process of manually containerizing a Python application from scratch and deploying it to CloudBase Cloud Hosting. The project uses flask as the web framework and 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
The project root directory must contain the following files:
├── .dockerignore
├── Dockerfile
├── README.md
├── main.py
└── requirements.txt
.dockerignore
: Used to specify files and directories to exclude when building Docker images. By using a.dockerignore
file, you can reduce image size and build time.Dockerfile
: A text file containing a series of instructions that define how to build a Docker image. By writing a Dockerfile, you can automate the creation of images containing 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 Python packages and their versions required by the application, used to install dependencies when building the Docker image.
Step 1: Write the Basic Application
Create a new directory named helloworld-python
and navigate into it:
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 creates a basic Web server and listens 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 to requirements.txt
.
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 Virtual Environment
python -m venv env
source env/bin/activate # Activate Virtual EnvironmentInstall dependencies and generate requirements.txt
pip install Flask gunicorn
pip freeze > requirements.txt
Generating a requirements.txt file using pip freeze
must be performed within a python virtual environment; otherwise, the generated requirements.txt will include all dependencies installed system-wide, which may cause deployment to fail.
Step 3: Containerize the Application
In the project root directory, create a file named Dockerfile
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 the 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 directory
# 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 Web Service
# If your container instance has multiple CPU cores, we recommend setting the thread count to match 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
Then you can 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 Run
If you have already installed the 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 Specification
- Configuration is typically placed in the project directory or configured using environment variables.
- During service deployment, simply specify the service's startup port 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 speed up dependency installation
- Set the container time zone appropriately
- Use .dockerignore to exclude unnecessary files
- Use gunicorn as the WSGI server for production environments
For Python framework project samples, you can refer to: