Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ArthurDelannoyazerty/dc009a45760cdd33e4d6fe0b8621d0e0 to your computer and use it in GitHub Desktop.
Save ArthurDelannoyazerty/dc009a45760cdd33e4d6fe0b8621d0e0 to your computer and use it in GitHub Desktop.
Simple Flask socketIO + nginx + gunicorn

from https://medium.com/@mosaif.ali.39/python-socket-io-flask-nginx-docker-awesome-microservice-bonus-android-client-07830a49a3d1

flask app

./requirements.txt

Flask
Flask-SocketIO
gunicorn[gevent]

./flask_app/app.py

from flask import Flask
from flask_socketio import SocketIO, emit
import logging
logging.basicConfig(level=logging.INFO)
# Create Flask app
app = Flask(__name__)
app.config['SECRET_KEY'] = 'test_secret'

# Initialize SocketIO
socketio = SocketIO(app, cors_allowed_origins="*",async_mode="gevent")

@app.route("/data_transmission_socket/version", methods=["GET", "POST"])
def versionPrint():
    return "%s" % "dev-socket-http-req"

# Test event for connection health check
@socketio.on('ping')
def handle_ping(data):
    logging.info('Server Pinged')
    # You can log or process the data received from the client (optional)
    logging.info(f"Received data: {data}")
    emit('pong', {'status': 'OK'})

# Handle client connection
@socketio.on('connect')
def on_connect():
    logging.info('Client connected')
    emit('connected', {'message': 'Connection established'})

# Handle client disconnection
@socketio.on('disconnect')
def on_disconnect():
    logging.info('Client disconnected')
    print("Client disconnected")

# Only run the app if executed directly (used in development only)
if __name__ == '__main__':
    socketio.run(app, port=5000)

./Dockerfile

FROM python:3.10-slim-buster

WORKDIR /usr/src/app/

COPY requirements.txt requirements.txt
RUN pip3 install --upgrade pip
RUN pip3 install -r requirements.txt

COPY . .

EXPOSE 5000

CMD gunicorn 'flask_app.app:app' \
    --worker-class gevent \
    --workers 1 \
    --bind 0.0.0.0:5000 \
    --reload \
    --access-logfile - \
    --error-logfile -

Nginx

./Dockerfile

FROM nginx:latest
RUN apt-get update && apt-get install -y procps

./nginx/conf.d/default.conf

upstream socketio_nodes {
     server data-transmission-socket:5000;
}

server {
    listen 80;
    client_max_body_size 100M;

    # for http requests
    location / { 
        proxy_pass http://socketio_nodes;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
    }
    # for socket connection
    location /socket.io {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_pass http://socketio_nodes/socket.io;
    }

    location /static/ {
        alias /usr/src/app/static/;
    }
}

docker compose

docker-compose.yml

services:  
  
  data-transmission-socket:
    build: ./data-transmission-socket/
    ports:
      - "5000:5000"
  
  nginx:
    build:
      context: ./nginx/
    ports:
      - 80:80
    volumes:
      - ./nginx/conf.d/:/etc/nginx/conf.d/
    depends_on:
      - data-transmission-socket
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment