DEV Community

Cover image for Bind for 0.0.0.0:8080 failed: port is already allocated
Simone Gentili
Simone Gentili

Posted on

Bind for 0.0.0.0:8080 failed: port is already allocated

Waiting for docker-compose to complete its execution, only to be greeted with the frustrating message that the desired port is not available, can be incredibly exasperating. The anticipation builds up as we hope for a seamless deployment, only to be let down by the port conflict. This can lead to wasted time and effort, not to mention the frustration of having to go back and manually find an available port.

However, with the help of this script, such moments of disappointment are now a thing of the past.

$fileContents = file_get_contents('docker-compose.yml.dist');
$generatedContents = str_replace('{{port}}', findFreePort(8080), $fileContents);

file_put_contents('docker-compose.yaml', $generatedContents);

function findFreePort($startPort)
{
    $port = $startPort;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    while (!@socket_bind($socket, '127.0.0.1', $port)) {
        $port++;
    }

    socket_close($socket);
    return $port;
}
Enter fullscreen mode Exit fullscreen mode

This is an example:

version: '3.7'
services:
  server:
    build:
      context: ./docker/server/
    volumes:
      - ./:/var/www/html
    ports:
      - "{{port}}:80"
Enter fullscreen mode Exit fullscreen mode

The beauty of not having to rely on trial and error anymore cannot be overstated. Gone are the days of guessing and manually changing port numbers until finding one that works. With this script in hand, the process becomes smooth and efficient. It automatically searches for an available port, starting from a specified point, such as 8080, eliminating the hassle of port conflicts. Now, docker-compose can effortlessly allocate a free port, saving valuable time and providing a sense of relief. The convenience and peace of mind offered by this script are truly remarkable.

Top comments (2)

Collapse
 
metalarend profile image
Bart Reunes

Try docker compose, without a dash. But to solve the port issue, if you don't mention the second port, docker will solve this problem for you. And if you want to never use a port again, check out traefik.

Collapse
 
sensorario profile image
Simone Gentili

But, ... If I have complex docker-compose file and a lot of services, ... how your trick works. I need to run docker compose for every service?