Logo

dev-resources.site

for different kinds of informations.

Bind for 0.0.0.0:8080 failed: port is already allocated

Published at
6/5/2023
Categories
php
docker
dockercompose
devop
Author
sensorario
Categories
4 categories in total
php
open
docker
open
dockercompose
open
devop
open
Author
10 person written this
sensorario
open
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.

Featured ones: