The most common docker commands

Nowadays I am using docker all the time. Yet sometimes I forget some switch or workflow. So to remember better and have it easily available, I decided to write down couple most common things one might want to (or rather port my Evernotes to blog ^^). Here it goes.

1. Create a custom image

Let’s create a simple docker image specifying container running HTTP server on port of our choice. By convetion must have name Dockerfile.

This is the directory structure to be used.

RUN runs specified command in built-time of the image. Use this to pre-prepare the state of container – create files, install and configure software…
COPY copies file from host to destination in container. If source path is relative, it is relative to location of Dockerfile.
ENV = sets value of environment variable inside container
CMD specifies process which should be executed on start of container, unless overriden.

Now to have that image actually available in local repository, run

and verify its presence docker images | grep hello

 

2. Run detached container with exposed port

Run container of hello_image, exposes it’s port 8080 and maps it to port 9000 on your Dockermachine (if you use Docker for Mac).

 

3. Pass environment variable to docker container

-e passes environment variable to container and override its value if it was already predefined in image at build-time of the image. In this specific cause, passing HELLO_PORT will change the port on which python HTTP server runs.

 

4. Get inside a running container and mess it up

Run container

Get inside and mess it all up

The important part here are -t-i switches!

 

5. Create image from handcrafted container

Not a good practice, but you can edit container manually and then turn it into image – letting you restore the state of your handcrafted container anytime on demand. Get inside running container just like described in point 4, modify whatever you want. Exit container and preserve it’s state into image as

Now you can run it anytime

 

6. Execute single command in container with output

Assuming container hello_cnt is running. Run

 

7. Mount a directory to container

Run

Mounts content of /home/user/foo to directory /mnt in container. You can verify it works

 

8. Create a link from one image to another

Useful feature which adds a new record to /etc/hosts. Run first image

And now run second image, which will have link to the first one

Now container client_cnt refers to hello_cnt container under alias link.hello, you can verify

Leave a Reply

Your email address will not be published. Required fields are marked *