C
C
coderisimo2020-06-01 15:44:57
PHP
coderisimo, 2020-06-01 15:44:57

How to set up web sockets on docker with PHP and nginx?

Tried to solve the problem for several days. Unfortunately, there is no result.
Bottom line - I want to set up work with web-sockets on docker , php and nginx. I will try to describe in detail how everything is configured.
I use workerman. When I start I get:

------------------------------------------- WORKERMAN --------------------------------------------
Workerman version:4.0.5          PHP version:7.2.24
-------------------------------------------- WORKERS ---------------------------------------------
proto   user            worker          listen                      processes    status           
tcp     root            omg             websocket://0.0.0.0:8282    4             [OK]            
--------------------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success.

i.e. it works.
Docker PS
b9beab6b1e51        nginx:latest        "nginx -g 'daemon of…"   36 seconds ago      Up 35 seconds       0.0.0.0:8000->80/tcp     pwa_nginx_1
b4583dd4af96        pwa_php             "docker-php-entrypoi…"   37 seconds ago      Up 36 seconds       8282/tcp, 9000/tcp       pwa_php_1
978dc6e1e1cb        mariadb             "docker-entrypoint.s…"   4 days ago          Up 37 seconds       0.0.0.0:3306->3306/tcp   pwa_mysql_1

docker-compose :

version: '2'
services:
    nginx:
      # используем последний стабильный образ nginx
        image: nginx:latest
        # маршрутизируем порты
        ports:
            - "8000:80"      
        # монтируем директории, слева директории на основной машине, справа - куда они монтируются в контейнере
        volumes:
            - ./hosts:/etc/nginx/conf.d
            - ./www:/var/www
            - ./logs:/var/log/nginx
        # nginx должен общаться с php контейнером
        links:
            - php
    php:
        # у нас свой образ для PHP, указываем путь к нему и говорим что его надо собрать
        build: ./images/php
        expose: 
            - "8282"

        # этот образ будет общаться с mysql
        links:
            - mysql
        # монтируем директорию с проектами
        volumes:
            - ./www:/var/www
    mysql:
        image: mariadb
        ports:
            - "3306:3306"
        volumes:
            - ./mysql:/var/lib/mysql
        # задаем пароль для root пользователя
        environment:
            MYSQL_ROOT_PASSWORD: secret


nginx

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
    }

server {
    charset utf-8;
    client_max_body_size 256M;

    listen 80; ## listen for ipv4
    #listen [::]:80 default_server ipv6only=on; ## listen for ipv6
    root        /var/www/distancer/web;
    index       index.php;

    server_name distancer;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;

    location /ws {
        proxy_pass http://php:8282/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        #added from https://github.com/walkor/Workerman/issues/248
        proxy_set_header X-Real-IP $remote_addr;
        proxy_read_timeout 950s;   
        proxy_set_header Host $http_host;
    }

    location / {
        # Redirect everything that isn't a real file to index.php
        try_files $uri $uri/ /index.php$is_args$args;
    }

  
    location ~ ^/assets/.*\.php$ {
        deny all;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass php:9000;
        fastcgi_read_timeout 500;
        try_files $uri =404;
    }
    location ~* /\. {
        deny all;
    }

}



js code

var conn = new WebSocket('ws://127.0.0.1');
            conn.onopen = function (e) {
                console.log("Connection established!");
            };



The site itself is working fine. Everything opens without problems. Sockets don't work.
I tried different configs for docker and nginx in a million combinations and variations (danced with a tambourine for glory!).
The error persists, the eye twitches.
Request ws://127.0.0.1 - gives net::ERR_CONNECTION_REFUSED or Error during WebSocket handshake: Unexpected response code: 200.
It seems that the topic is standard, but I can’t find clear recipes for a solution. A bunch of different variants, equally useless.
Tried forwarding php outside and accessing it directly.
expose - "8282:8282" , get the IP of the php container (eg 127.0.21.1) via inspect and access ws://127.0.21.1:8282. The result is the same.

in general, I will be glad to ideas, comments And so on.
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
coderisimo, 2020-06-01
@coderisimo

Suggested by Andrey Shatokhin You just need to contact ws: //127.0.0.1
:8000/ws , but I tried like this ws://127.0.0.1:8000/ - without /ws at the end
Accordingly , the location /ws in the nginx config did not work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question