Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker: How to start an existing container and forward the ports?

I am new to docker and I'm trying to get a permanent installation of Rancher started. To create the docker container I run the following command:

docker run -d --name rancher-server -p 8080:8080 rancher/server

Note that I want to forward the container's 8080 port to my hosts' 8080, since 80 is occupied by nginx on my host.

Now, when I stop the above container and try to start it again using docker start <Container ID> I get the following error:

Error response from daemon: driver failed programming external connectivity on endpoint rancher-server (c18940f957ed1f737fd5453ea29755adea762d758643a64984d5e3ce8bd3fdbe): Error starting userland proxy: listen tcp 0.0.0.0:80: bind: address already in use Error: failed to start containers: c93794a8c0ad

I know that this happens since nginx is using port 80, so my question is how do I start my existing container and tell it to forward its ports?

Running docker start -d -p 8080:8080 c93794a8c0ad gives me the following error: unknown shorthand flag: 'd' in -d

So how do I start a container with forwarded ports? Thank you!

like image 777
Lucas P. Avatar asked Jul 22 '18 19:07

Lucas P.


1 Answers

The problem might be that two programs are working on the same port. You can change the port settings when you are running the docker run command. For instance, you can bind port 8080 of the container with an arbitrary port on your computer, like 8081:

docker run -d --name rancher-server -p 8081:8080 rancher/server

The left-hand port number is the docker host port - your computer - and the right-hand side is the docker container port.

You CAN modify the ports

You can change the ports of a docker container without deleting it. The way quin452 puts it - with minor revision:

  1. Get the container ID:

    docker ps -a

  2. Stop the container:

    docker stop [container name]

  3. Edit the container hostconfig.json file, found at

    var/lib/docker/containers/[container ID]/hostconfig.json

  4. Within the PortBindings section, either edit the existing HostPort to the port you would like, or add them yourself (see below)

  5. Save and exit the config file

  6. Restart docker:

    sudo systemctl restart docker

  7. Start up the container:

    docker start [container name]

An example config file:

"PortBindings": {
    "3306/tcp": [
        {
            "HostIp": "",
            "HostPort": "23306"
        }
    ],
    "443/tcp": [
        {
            "HostIp": "",
            "HostPort": "2443"
        }
    ],
    "80/tcp": [
        {
            "HostIp": "",
            "HostPort": "280"
        }
    ]
}
like image 135
Pedram Avatar answered Nov 15 '22 06:11

Pedram