dotcloud/docker — pull request #4628 by kippandrew (2014-03-12 21:57:09+00:00)
Title: Fix port collision with dynamically allocated ports

Currently its possible for a container to fail to start because the portallocator can allocate a dynamic port that is currently in use. This PR fixes the issue by ensuring that a dynamically allocated port is not in use before assigning it.

This is most likely to happen when you have running containers and restart the docker daemon. Docker will start the containers back up on their previously allocated port(s), but new containers will still attempt to allocate these ports and fail to start. Looks to be a problem since 0.8.0 (no issues in 0.7.6 and earlier).

Steps to reproduce:

```
$ docker run -t -i -d -p :8000 base
27627ddc8084093cee8c6adc9eecaadc19fe9153b41bbc47d8882227a0593464

$ sudo service docker restart
docker stop/waiting
docker start/running, process 5945

$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
27627ddc8084 base:latest bash 16 seconds ago Up 3 seconds 0.0.0.0:49153->8000/tcp lonely_mccarthy

$ docker run -t -i -d -p :8000 base bash
8d9face480f2774f528b7f7e338fde9c039b57ec7ebe6f09815e53884fbae2ea
2014/03/12 17:54:11 Error: start: Cannot start container 8d9face480f2774f528b7f7e338fde9c039b57ec7ebe6f09815e53884fbae2ea: allocate_port: port is already mapped to ip
```