Skip to content

Despliegue Python

Integración con Traefik y base de datos opcional.

Añadir al archivo /root/docker-compose.yml:

python-app:
build:
context: ./proyecto-python
container_name: python-app
restart: unless-stopped
env_file:
- ./proyecto-python/.env
labels:
- traefik.enable=true
- traefik.http.routers.python-app.rule=Host(`python.tudominio.com`)
- traefik.http.routers.python-app.tls=true
- traefik.http.routers.python-app.entrypoints=web,websecure
- traefik.http.routers.python-app.tls.certresolver=mytlschallenge
- traefik.http.services.python-app.loadbalancer.server.port=8000

Añadir también:

postgres:
image: postgres:16-alpine
container_name: postgres
restart: unless-stopped
environment:
POSTGRES_DB: myapp
POSTGRES_USER: myuser
POSTGRES_PASSWORD: cambiar_password_seguro
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:

Actualizar python-app:

python-app:
build:
context: ./proyecto-python
container_name: python-app
restart: unless-stopped
depends_on:
- postgres
environment:
- DATABASE_URL=postgresql://myuser:cambiar_password_seguro@postgres:5432/myapp
labels:
# ... (mismos labels)

Crear .env en el proyecto:

# Flask
FLASK_ENV=production
SECRET_KEY=tu_clave_secreta_aqui
# Django
DEBUG=False
SECRET_KEY=tu_clave_secreta_aqui
ALLOWED_HOSTS=python.tudominio.com,tudominio.com
DATABASE_URL=postgresql://user:pass@postgres:5432/dbname
# FastAPI
ENVIRONMENT=production
Terminal window
cd /root
docker compose build python-app
docker compose up -d python-app
# Con PostgreSQL
docker compose up -d postgres python-app
Terminal window
docker exec -it python-app python manage.py migrate
docker exec -it python-app python manage.py collectstatic --noinput
docker exec -it python-app python manage.py createsuperuser
Terminal window
docker compose logs -f python-app

Acceder a https://python.tudominio.com.

labels:
- traefik.enable=true
- traefik.http.routers.python-app.rule=PathPrefix(`/api`)
- traefik.http.routers.python-app.tls=false
- traefik.http.routers.python-app.entrypoints=web
- traefik.http.services.python-app.loadbalancer.server.port=8000

Acceder: http://TU_IP/api