title: How to connect a socket with Socket.io in a Docker container?
body: <p>I have a tiny socket server in a docker container the server looks like </p>
  
  <pre><code>var app = require('express')();
  var server = require('http').Server(app);
  var io = require('socket.io')(server, {origins: 'localhost:*'});
  io.on('connection', function (socket) {
  console.log('Connected');
  });
  const PORT = 8081;
  const HOST = '0.0.0.0';
  server.listen(PORT, HOST);
  </code></pre>
  
  <p>and the docker file is </p>
  
  <pre><code>FROM keymetrics/pm2-docker-alpine:latest
  WORKDIR /root
  RUN apk update &amp;&amp; \
     apk upgrade &amp;&amp; \
     apk add git
  ENV HOME /root
  COPY socket.js ./
  COPY package.json ./
  RUN npm install
  COPY pm2.json ./
  EXPOSE 8081
  CMD [ "pm2-docker", "start", "pm2.json" ]
  </code></pre>
  
  <p>pm2.json looks like</p>
  
  <pre><code>{
  "apps": [{
      "name": "socket-server",
      "script": "socket.js",
      "exec_mode" : "cluster",
      "instances"  : 2,
      "env": {
      "production": true
      }
  }]
  }
  </code></pre>
  
  <p>package.json</p>
  
  <pre><code>{
  "name": "socket-server",
  "version": "1.0.0",
  "description": "",
  "main": "socket.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  "express": "^4.15.3",
  "socket.io": "^2.0.3"
  }
  }
  </code></pre>
  
  <p>It all runs just fine with</p>
  
  <pre><code>docker run -d -p 8081:8081 socket-server
  </code></pre>
  
  <p>until I try to connect to it from a website running in another container, the website connects like this...</p>
  
  <pre><code>&lt;script src="socket.io.js"&gt;&lt;/script&gt;
  &lt;script&gt;
    var socket = io.connect('http://localhost:8081');
    socket.on('connect', function(data) {
      console.log('Connected Client')
    });
  &lt;/script&gt;  
  </code></pre>
  
  <p>and in the console, it shows that it polls just fine with</p>
  
  <pre><code>Request URL:http://localhost:8081/socket.io/?
  EIO=3&amp;transport=polling&amp;t=LthQCgI&amp;sid=93sOyTiSOe5RVOdEAAAL
  Request Method:POST
  Status Code:200 OK
  </code></pre>
  
  <p>but fails to get a socket connection </p>
  
  <pre><code>Request URL:ws://localhost:8081/socket.io/?
  EIO=3&amp;transport=websocket&amp;sid=93sOyTiSOe5RVOdEAAAL
  Request Method:GET
  Status Code:400 Bad Request
  </code></pre>
  
  <p>Now if I run the socket server, not in the docker container it's fine and the socket connects. </p>
  
  <p>I have tried getting the IP of the container that the socket server is running and using that in the connection script but even the polling doesn't work when I configure it like that.</p>
  
  <p>I really need this inside a Docker container.</p>
  
  <p>Any help is most appreciated</p>