Basic Docker Commands
Some Concepts First
- Image: Image not only contains the application itself, but also the environment, configurations and libraries for it.
- Container: A seperate environment that Docker creats when running an image. It is like a virtual machine.
- Docker Hub: A public repo for images. You can also find docs from image providers.
Common Commands about Images
docker pull
: download image from repository.docker images
: check all downloaded images.docker rmi
: remove image.docker build
: build an image from a dockerfile.docker save
: save an image to a compressed file.docker load
: load an image from a compressed file.docker push
: push an image to repository.
To get help for a certain command, such as docker save
: docker save --help
Common Commands about Containers.
docker run
: create a container and run an image in it.docker stop
: stop a container (not delete).docker start
: start a (created) container.docker ps
: check running containers.docker rm
: remove a container.docker logs
: check logs (usually use-f
to see latest logs).docker exec
: enter a container.
Example: Mysql with Docker
docker run -d --name ms -p 3307:3306 -e TZ=Asia/Shanghai -e MYSQL_ROOT_PASSWORD=123 mysql
docker run
: Create and run container.-d
means run in background.--name ms
: Set the name of the container toms
. It should be unique.-p 3307:3306
: Container is an independent environment which have its own ports, and it is not visible to outer environment. This option will connect the3307
port of the machine to the3306
port of the container. Now you can access the3307
port of the physical machine to access the mysql service.-e KEY=VALUE
: Set environment variables. It depends on the images. You can check the necessary variables on Docker Hub.mysql
: The image to be run. The complete format looks likemysql:5.7
. If version is not provided, then the latest version will be used by default.
Now a MySQL service should be accessible at port 3307 of the machine.
Example: Nginx with Docker
1. Pull the image
docker pull nginx
To check local images:
docker images
2. Create and run a container
docker run -d --name nginx -p 80:80 nginx
To check running containers:
docker ps # too long. the one below is better.
docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Ports}}\t{{.Status}}\t{{.Names}}" # You may want to set an alias for this line
Note that docker ps
gives running container by default. To check all containers including the stopped ones:
docker ps -a
3. Enter a container
docker exec -it nginx bash
-it
gives a terminal.nginx
is the name of the container.bash
is the command to execute. Here a bash will be opened.
Now you have "entered the virtual computer". You can execute commands just like on a real computer.