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.

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 containerCMD specifies process which should be executed on start of container, unless overriden.

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

1

docker build--tag hello_image

and verify its presence docker images | grep hello

2. Run detached container with exposed port

1

docker run--name hello_cnt-tid-p9000:8080hello_image

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

1

docker run--name hello_cnt-tid-eHELLO_PORT=9999-p9000:9999hello_image

-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

1

docker run--name hello_cnt-tid hello_image

Get inside and mess it all up

1

docker exec-ti hello_cnt/bin/bash

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

1

docker commit hello_cnt hello_img_edit

Now you can run it anytime

1

docker run-tid--name edited_cnt hello_img_edit

6. Execute single command in container with output

Assuming container hello_cnt is running. Run

1

docker exec-thello_cnt ls-l/

7. Mount a directory to container

Run

1

docker run--name foo_cnt-v/home/user/foo:/mnt centos:7

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