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
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
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;
if you want to use the same container over and over again, just use the docker start command.
Please note,
-it
for interactive access either ondocker start
ordocker run
. If you don’t want to access the container withtty
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.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
Stop and remove your container, and then run the new image with
-p
and-v
like:Note that
commit
can cost a lot of time if your container is large(a lot of data in container layer).Good luck!