Skip to content

davy1ex/ReactPythonTemplateFullstack

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Docker Python React Template

A production-ready template for rapid deployment of full-stack Flask-React applications with Docker.

Use Cases

This template is perfect for:

  • MVPs and prototypes - Get your idea up and running quickly
  • Personal projects - Full-stack setup without the boilerplate
  • Learning - Understand Docker, Flask, React integration
  • Production applications - Built with production-ready configurations
  • Client projects - Professional starting point with best practices

Features at a Glance

  • Fast setup - Running in minutes with one command
  • Hot reload - Both frontend and backend with instant feedback
  • Dockerized - Consistent environment across all machines
  • Nginx proxy - Production-ready reverse proxy setup
  • Modular - Easy to add databases, auth, APIs, UI libraries
  • Dev/Prod modes - Separate optimized configurations
  • Well documented - Clear guides for requests, logs, architecture

Table of Contents

Purpose

This repository serves as a ready-to-use template for quickly scaffolding full-stack web applications. It provides:

  • Complete Docker setup with development and production configurations
  • Flask backend with hot reload and proper request logging
  • React + Vite frontend with modern tooling and HMR
  • Nginx reverse proxy configured for both dev and prod environments
  • Extensible architecture - add features, routes, and components easily

Use this as a starting point and customize it for your specific application needs. The template is designed to be extended, not just used as-is.

Getting Started with Template

Create your project from this template:

# Clone the repository
git clone https://github.com/davy1ex/ReactPythonTemplateFullstack
cd ReactPythonTemplateFullstack

# Setup environment variables
cp backend/env.example backend/.env
cp frontend/env.example frontend/.env
# Edit .env files if needed (optional for quick start)

# Start project
cd docker
docker-compose up --build

Access your application at http://localhost

Architecture

┌─────────────────────────────────────────────┐
│             Nginx (Port 80)                 │
│  ┌─────────────────┬───────────────────┐    │
│  │   / (Frontend)  │  /api (Backend)   │    │
│  └────────┬────────┴─────────┬─────────┘    │
└───────────┼──────────────────┼──────────────┘
            │                  │
     ┌──────▼──────┐    ┌─────▼──────┐
     │   React     │    │   Flask    │
     │   Vite      │    │   Python   │
     │  Port 5173  │    │  Port 5001 │
     └─────────────┘    └────────────┘

Project Structure

.
├── docker/
│   ├── docker-compose.yml         # Development environment
│   ├── docker-compose.prod.yml    # Production environment
│   └── nginx/
│       ├── Dockerfile
│       ├── nginx.dev.conf         # Development config (proxy to Vite)
│       └── nginx.prod.conf        # Production config (serve static files)
├── frontend/
│   ├── src/
│   │   ├── App.jsx
│   │   ├── App.css
│   │   ├── main.jsx
│   │   └── index.css
│   ├── public/
│   ├── Dockerfile
│   ├── package.json
│   ├── vite.config.js
│   ├── index.html
│   └── env.example                # Environment variables template
└── backend/
    ├── server.py
    ├── requirements.txt
    ├── Dockerfile
    └── env.example                # Environment variables template

Quick Start

The project supports two modes:

  • Development Mode - Hot reload for both frontend and backend, volume-mounted code for instant changes, Vite dev server with HMR
  • Production Mode - Optimized production build, minified static files, Gunicorn WSGI server, Nginx serving built assets

Choose the mode based on your needs. Development mode is recommended for active development, while production mode is for testing the deployment setup or actual deployment.

Development Mode (with hot reload)

# First time setup: Create .env files
cp backend/env.example backend/.env
cp frontend/env.example frontend/.env

# Start all services
cd docker
docker-compose up --build

# Access the application
# Frontend + Backend: http://localhost
# Frontend only (Vite): http://localhost:5173
# Backend only: http://localhost:5001

Important: .env files are required. Copy from env.example files before first run.

The development environment includes:

  • ✅ Hot reload for React (Vite dev server on port 5173)
  • ✅ Hot reload for Flask (volume mounted)
  • ✅ Nginx reverse proxy routing
  • ✅ Volume mounting for live code changes

Adding Dependencies

Frontend packages (no rebuild needed):

# Install directly on host machine
cd frontend
npm install <package-name>

# Changes are immediately available in container!

Backend packages (rebuild required):

# Add to requirements.txt
cd backend
echo "requests==2.31.0" >> requirements.txt

# Rebuild backend container
cd ../docker
docker-compose up --build backend

💡 Important: Frontend folder is mounted as volume, so npm install works directly. Backend code has hot reload, but new Python dependencies need container rebuild.

Production Mode

# Setup production .env files with production values
cp backend/env.example backend/.env
cp frontend/env.example frontend/.env
# Edit .env files: set FLASK_ENV=production, strong SECRET_KEY, etc.

# Build and start production services
cd docker
docker-compose -f docker-compose.prod.yml up --build

# Access the application at http://localhost

Important: For production, update .env files with secure values (especially SECRET_KEY).

The production environment includes:

  • ✅ Optimized React build (static files)
  • ✅ Gunicorn WSGI server for Flask
  • ✅ Nginx serving static files + API proxy
  • ✅ Production-ready configurations

Development

Backend (Flask)

The Flask server runs on port 5001 and provides API endpoints:

  • GET /api/health - Health check
  • GET /api/hello?name=YourName - Hello endpoint
  • POST /api/data - Example POST endpoint

For adding dependencies, see Quick Start → Adding Dependencies.

Frontend (React + Vite)

The React app runs on Vite dev server (port 5173) with hot module replacement.

For adding dependencies, see Quick Start → Adding Dependencies.

Nginx Configuration

  • Development (docker/nginx/nginx.dev.conf):

    • Routes / to Vite dev server (port 5173) with WebSocket support
    • Routes /api to Flask backend (port 5001)
  • Production (docker/nginx/nginx.prod.conf):

    • Serves built React static files from /usr/share/nginx/html
    • Routes /api to Flask backend (port 5001)
    • Includes caching and security headers

Common Commands

# Navigate to docker folder
cd docker

# Start services
docker-compose up

# Start services in background
docker-compose up -d

# Stop services
docker-compose down

# View logs
docker-compose logs -f

# View logs for specific service
docker-compose logs -f backend

# Rebuild specific service
docker-compose up --build frontend

# Execute command in running container
docker-compose exec backend python -m pytest
docker-compose exec frontend npm test

# Access container shell
docker-compose exec backend sh
docker-compose exec frontend sh

Testing the Setup

Development Mode Testing

After starting the development environment with docker-compose up:

  1. Open http://localhost in your browser
  2. Click "Test Backend Connection" button
  3. You should see a success message from the Flask backend

Test hot reload (Development only):

Frontend:

  • Edit frontend/src/App.jsx
  • Changes should appear immediately in the browser (Vite HMR)

Backend:

  • Edit backend/server.py
  • Flask will auto-reload automatically (may take a few seconds)

Production Mode Testing

After starting the production environment with docker-compose -f docker-compose.prod.yml up:

  1. Open http://localhost in your browser
  2. The application will serve optimized, built static files
  3. Backend runs with Gunicorn (multi-worker production server)

Differences in Production:

  • ⚠️ No hot reload - Changes require rebuild
  • Optimized frontend - Minified and bundled with Vite build
  • Production server - Gunicorn instead of Flask dev server
  • Better performance - Static file serving and caching headers

To rebuild after changes in production mode:

cd docker
docker-compose -f docker-compose.prod.yml up --build

Extending the Template

This template is designed to be easily extended. Here are common customizations:

Frontend Extensions

Add new pages/routes:

cd frontend
npm install react-router-dom
# Create components in frontend/src/components/
# Update App.jsx with routing logic

Add UI library:

cd frontend
# Material-UI
npm install @mui/material @emotion/react @emotion/styled

# Or TailwindCSS
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Add state management:

cd frontend
# Redux Toolkit
npm install @reduxjs/toolkit react-redux

# Or Zustand
npm install zustand

Example: Add a new feature component

// frontend/src/components/UserProfile.jsx
export function UserProfile() {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    fetch('/api/user/profile')
      .then(res => res.json())
      .then(data => setUser(data));
  }, []);
  
  return <div>{user?.name}</div>;
}

Backend Extensions

Add new API endpoints:

# backend/server.py
@app.route('/api/users', methods=['GET'])
def get_users():
    users = [{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}]
    return jsonify(users)

@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    return jsonify({"id": user_id, "name": "John Doe"})

Add authentication:

# Add JWT or Flask-Login
# Update backend/requirements.txt:
# flask-jwt-extended==4.6.0
# flask-login==0.6.3

docker-compose up --build backend

Structure your backend with blueprints:

# backend/routes/users.py
from flask import Blueprint

users_bp = Blueprint('users', __name__)

@users_bp.route('/api/users')
def list_users():
    return jsonify([])

# backend/server.py
from routes.users import users_bp
app.register_blueprint(users_bp)

Add ORM for database:

# Add to requirements.txt:
# Flask-SQLAlchemy==3.1.1
# Flask-Migrate==4.0.5

# Create models in backend/models/
# Initialize database with Flask-Migrate

Quick Customization Checklist

Before starting your project, customize:

  • Create .env files: cp backend/env.example backend/.env and cp frontend/env.example frontend/.env
  • Update SECRET_KEY in backend/.env for production
  • Change package.json name and version
  • Update frontend title in frontend/index.html
  • Configure CORS settings in backend/server.py if needed
  • Update Nginx server names if deploying to custom domain
  • Customize frontend styling and branding
  • Add your API endpoints in backend
  • Add your React components in frontend

Adding a Database

Example with PostgreSQL:

  1. Add to docker/docker-compose.yml:
  postgres:
    image: postgres:15-alpine
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    volumes:
      - postgres-data:/var/lib/postgresql/data
    networks:
      - app-network

volumes:
  postgres-data:
  1. Update backend/requirements.txt:
psycopg2-binary==2.9.9
SQLAlchemy==2.0.23

Environment Variables

The project uses separate .env files for each service. Each service has an env.example file that works for both development and production.

Setup for Development:

# Copy example files
cp backend/env.example backend/.env
cp frontend/env.example frontend/.env

# Default values in env.example are ready for development!
# You can start immediately or customize if needed.

Setup for Production:

# Copy example files
cp backend/env.example backend/.env
cp frontend/env.example frontend/.env

# Edit backend/.env for production:
# 1. Change FLASK_ENV=development to FLASK_ENV=production
# 2. Change FLASK_DEBUG=1 to FLASK_DEBUG=0
# 3. Generate strong SECRET_KEY: python -c "import secrets; print(secrets.token_hex(32))"
# 4. Update DATABASE_URL if using database

# Edit frontend/.env for production:
# 1. Change NODE_ENV=development to NODE_ENV=production
# 2. Update VITE_API_URL if needed

Backend .env example:

FLASK_ENV=development          # Change to 'production' for prod
FLASK_DEBUG=1                  # Change to 0 for prod
SECRET_KEY=dev-secret-key      # MUST change for prod!
DATABASE_URL=postgresql://...  # Optional

Frontend .env example:

NODE_ENV=development           # Change to 'production' for prod
VITE_API_URL=/api             # API endpoint
CHOKIDAR_USEPOLLING=true      # For dev hot reload

Note: .env files are gitignored. The env.example files contain inline comments explaining what to change for production.

Security Notes

For production deployment:

  1. Use environment variables for sensitive data
  2. Set up HTTPS with SSL certificates
  3. Configure proper CORS policies
  4. Use secrets management (Docker secrets, K8s secrets)
  5. Update security headers in Nginx config
  6. Set strong SECRET_KEY for Flask

Troubleshooting

Port already in use

# Find and kill process using port 80
lsof -ti:80 | xargs kill -9

# Or change port in docker-compose.yml
ports:
  - "8080:80"  # Use port 8080 instead

Hot reload not working

# Ensure volumes are properly mounted
docker-compose down -v
docker-compose up --build

Frontend can't connect to backend

  • Check that all services are running: docker-compose ps
  • Check Nginx logs: docker-compose logs nginx
  • Verify network configuration

🤝 Contributing

Feel free to submit issues and enhancement requests to improve this template!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published