Here are all the basic commands you need to know to work with Docker in the development environment:
-
build an image named
myAppImage
from the current project folder (Dockerfile
must be present):$ docker build . -t myAppImage
-
run a container named
myAppContainer
from the image namedmyAppImage
. In interactive mode (pressingCtrl+C
will stop it):$ docker run -it --rm --name myAppContainer myAppImage
-
run a container the same way as in previous example and also:
- make the port
8080
on your host machine listen to the port3000
inside the container - make the folder
./data
on your host machine available inside the container as/data/db
$ docker run -it --rm --name myAppContainer -p 8080:3000 -v $(pwd)/data:/data/db myAppImage
- make the port
-
when you want to get inside the terminal of the running container named
myAppContainer
(whiledocker run -ti
is running in another terminal window) to check its filesystem or run any other commands (for example to runtop
ormongo
):$ docker exec -it myAppContainer sh
-
to view all currently running containers:
$ docker ps
-
to view all images you did build or download:
$ docker images
-
[CLEANUP] to force stop (if running) and remove the container named
myAppContainer
:$ docker rm -f myAppContainer
-
[CLEANUP] to remove the image named
myAppImage
:$ docker rmi myAppImage
HINTS:
docker ps
shows only the containers which are currently running (eat CPU and memory)docker ps -a
will also show the stopped containers (which don't eat CPU and memory, but still take space on your hard drive)- running the command
docker run
with the--rm
flag tells docker to autoremove the container when you pressCtrl+C
- if you always use
--rm
flag fordocker run
you won't have any stopped containers, and can simply usedocker ps
- you should avoid having stopped containers, because they eat your space, and you probably are not going to use them again after they were stopped. So it is recommend to always use
--rm
in development environment.
-
Cleanup all exited containers
$ docker ps -aq --no-trunc -f status=exited | xargs docker rm
-
Cleanup all untagged images
$ docker images -q --filter dangling=true | xargs docker rmi
Below is a fully documented example of a simple Dockerfile
for a node.js app which is supposed to listen for the port 3000: