genkio / blog

Stay hungry stay foolish
https://slashbit.github.io/blog/
0 stars 1 forks source link

Get started with Docker #145

Open genkio opened 7 years ago

genkio commented 7 years ago

Once you have docker community edition installed, you're ready to go. One key concept to clear out first, difference between image and container, container is the running instance of the image, put it another way, think image as the ISO file, and container as the "virtual machine" booted up by the image.

Kernel, image, container illustrated docker-layers

Alright, let's learn some basic commands.

To list all of the images

$ docker images

To list all of the containers

# `-a` to list all the inactive ones as well
$ docker ps -a

To verify installation

$ docker --version
# Docker version 17.03.0-ce, build 60ccb22

$ docker-compose --version
# docker-compose version 1.11.2, build dfed245

To pull a docker image (nginx for example) from docker hub

$ docker pull nginx:1.10.2-alpine

To run a image

# `80:80` to map the port inside of the container (80) to the local host machine port (80)
# this command will also pull the docker image if it's not there

$ docker run --name my-nginx -p 80:80 nginx:1.10.2-alpine
# `docker container run` is the new command for this operation

To stop a container

$ docker stop my-nginx

To re-start a existed container

$ docker restart my-nginx

To remove a container.

Once the container created, you can't change start up parameters, for example, to change the port mapping from 80 to 8080, if you want to make anyway changes, you have to remove it first.

$ docker rm my-nginx

To execute a command inside of an running container

# `-ti` to enable interactive mode
$ docker exec -ti my-nginx /bin/sh

To mount a file from host to the container and make it read-only

$ docker run --name my-nginx -v /Users/wu/Desktop/nginx.conf:/etc/nginx/nginx.conf:ro -p 80:80 nginx:1.10.2-alpine

To create your docker image

# `-t` for tagging (name:version)
# `.` for specifying the build context (where to look for the Dockerfile)
$ docker build -t zip-nginx:1.0 .

Dockerfile example

# base image
FROM rails:4.2.4
MAINTAINER User <user@example.com>
RUN mkdir -p /var/app
# set working directory
WORKDIR /var/app
COPY Gemfile /var/app/Gemfile
RUN bundle install
CMD rails s -b 0.0.0.0

To delete all containers and images

# delete all containers
docker rm $(docker ps -a -q)
# delete all images
docker rmi $(docker images -q)