skip to Main Content

I am a newbie to docker (containerization stuff). I am trying to learn docker in GCP (CentOS 7 instance) and to containerization my simple interactive python program. I successfully created a docker image for my python program.

My doubt is when I run

docker run -it my image name

A container is spinned up with a random name call “classy-brown”
and my program executed successfully …and no issue with that.

The thing is, is there any way to add port & volume for my existing container i.e(“classy-brown”)

And every time when I run this command

docker run -it my image name

A new container is created? And why its doing it me?

Please help me out with this.

3

Answers


  1. and welcome to StackOverflow.
    You can pass the “–name” parameter when you start a container, to give it a custom name.

    Also, you may use the ‘-p’ option to expose specific ports.

    Have a look at this page to see all the docker run options –

    https://docs.docker.com/v17.12/engine/reference/commandline/run/#options

    Login or Signup to reply.
  2. No, you can’t setup a volume or a port on already created container. You can use docker start -it <container_id> or <conatiner_name> to use a container multiple times interactively.

    If you want to setup a volume or port on a container, you should to it during the container creation using docker run command like this;

    docker run -p 80:80 -v /home/somedir:/foo --name my_container
    

    if you want to use the same container over and over again, just use the docker start command.

    docker start -it my_container
    

    Please note, -it for interactive access either on docker start or docker run. If you don’t want to access the container with tty just omit the -it flags.

    If you want to access already running container, you can use docker exec command. More about it you can find here.

    Login or Signup to reply.
  3. A new port mapping can be added by manually editing iptable rules, but I don’t think it is a good practice. Besides, if you run docker ps, this newly-added mapping will not be visible.


    If you REALY need to add port mappings or mount volumes to your already running container. You can commit this container to an image by

    docker commit <container-id>
    

    Stop and remove your container, and then run the new image with -p and -v like:

    docker run -p <port-mapping> -v <mount> <commited-image>
    

    Note that commit can cost a lot of time if your container is large(a lot of data in container layer).

    Don’t rely on this kind of approach too much, but think twice before you run your container.

    Good luck!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search