Default start up command (that will be executed inside that container) can also be defined in the image. The command should be availble in the file system snapshot of the image.
The image is pulled from the hub if it is not locally available
The run command creates the file system snapshot of the image in the hard drive
Eg, pull the image busybox and run the command ls (defined within the image) : lists the files in the file system snapshot of the image
docker run busybox ls
bin dev etc home proc root
Commonly used to get the container id (different from image id)
docker ps
Lists all running container
docker ps --all
Lists all the containers that have been run
Lists all images available locally
docker imagesTo remove an image
docker rmi [IMAGE_NAME]
docker run = docker create + docker start
#Creates the FS and execution command and outputs the container ID
docker create busybox ls
[CONTAINER_ID]
#Start that container (executes the command ls)
docker start -a [CONTAINER_ID]
#Running without -a does not print the output to terminal (Runs in background)
docker start [CONTAINER_ID]
#However, we can get the output with docker logs command
docker logs [CONTAINER_ID]
docker run creates a new container everytime. To restart the old container, get the container id from ps command and use docker start -a [CONTAINER_ID]
#Stops the running container
docker stop [CONTAINER_ID] #Process stops after its work is done. Invokes kill after 10s
docker kill [CONTAINER_ID] #Force stop
To delete all containers and unreferenced images
docker system prune
We ll demonstrate this use case with redis (This is a common usecase while working on servers)
In terminal 1
docker run redis
#Starts redis server and keeps running. We are not able to type additional commands in this terminal
(or)
docker run -d redis #runs the server in background and lets you use the same terminal
To run additional command in this container, open terminal 2
#Get CONTAINER_ID
docker ps
#user docker exec
# -it opens an (shell) environment where we can interact with the container
# -i connects the STDIN to the container
# -t makes the output appear formatted
docker exec -it [CONTAINER_ID] redis-cli
#opens client
127.0.0.1:6379>
127.0.0.1:6379>
To open linux env shell
docket exec -it [CONTAINER_ID] sh #can also use bash instead of sh, if it is defined @ redis-cli #assuming redis-server is up and running @127.0.0.1:6379> @127.0.0.1:6379>Can also open shell with run
docker run -it busybox sh