简体   繁体   中英

How to set up nginx in a Docker container in an Azure App Service with secure WebSockets (wss)?

I have 2 services running in a Docker container in an Azure App Service. I want to expose some APIs from each and one service also uses sockets. Everything works fine when using the Docker container locally (no SSL), but not when using the Azure App Service: if I go to the front end for my service, eg https://myservicename.azurewebsites.net , then there are errors creating a WebSocket connection. The DevTools says it's trying to connect to "wss://myservicename.azurewebsites.net/stream".

They are both Python services. One is a Flask service, the other uses Streamlit.

nginx.conf:

server {
    listen 8502;

    # One service runs on port 5000 (Python Flask).
    # It just uses HTTP requests.
    location /api/run {
        proxy_pass  http://localhost:5000/run;
    }

    location /api/results {
        proxy_pass  http://localhost:5000/results;
    }

    # The other service runs on port 8501 (Python Streamlit).
    # It uses HTTP requests, has a front end web page, and uses WebSockets.
    location / {
        proxy_pass http://localhost:8501;

        # Get web sockets to work too:
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

Dockerfile:

FROM mcr.microsoft.com/mirror/docker/library/python:3.9-slim

# Set up some environment variables.
...

EXPOSE 8502
RUN apt --yes update && apt --yes install curl nginx

COPY nginx.conf /etc/nginx/conf.d/my_app.conf

# Install some dependencies.
...

# Start nginx and my 2 services.
CMD nginx && \
    (poetry run python ./back_end/main.py & \
    poetry run streamlit run ./dashboard/dashboard.py)

What should I change so that secure WebSockets work in the Azure App Service? I've seen information about configuring SSL and certs in nginx configurations, but I thought I wouldn't have to worry about that because the Azure App Service handles the cert stuff for my app.

From the websocket-nginx docs, it seems your nginx.conf is missing the Host header

proxy_set_header Host $host;

I've had mixed experience with lack of capitalization for headers, so try "Upgrade" with a capital "U"

proxy_set_header Connection "Upgrade";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM