HostOnNet Blog

Running Docker Container

docker run command is used to run docker containers. If no docker container or image is present on your computer, docker will download it from dockerhub.

To run nginx container, run

root@hon-vpn:~# docker run -d nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
36a46ebd5019: Pull complete 
57168433389f: Pull complete 
332ec8285c50: Pull complete 
Digest: sha256:c15f1fb8fd55c60c72f940a76da76a5fccce2fefa0dd9b17967b9e40b0355316
Status: Downloaded newer image for nginx:latest
317b0369e3681d48263c6506bb713b165e185cc7ae1d3a2bbfd8c2eabf864326
root@hon-vpn:~# 

-d make docker container run in background.

-d, –detach Run container in background and print container ID

Now if you check with docker ps, you see nginx container running

root@hon-vpn:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
25cec84d12ff        nginx               "nginx -g 'daemon ..."   8 seconds ago       Up 6 seconds        80/tcp              flamboyant_golick
root@hon-vpn:~# 

Nginx is running on port 80, but it is not mapped to host machine, so there is no way you can access it outside the container.

To make nginx available to public, we need to use -p option to map ports.

root@hon-vpn:~# docker run -d -p 8000:80 nginx
594c77d773514746486ff3067da5f27da3796a3dc1653f651dcf757e0a049818
root@hon-vpn:~# 

This will map nginx running inside container to port 8000 on host computer. Lets check it with docker ps

root@hon-vpn:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
594c77d77351        nginx               "nginx -g 'daemon ..."   54 seconds ago      Up 51 seconds       0.0.0.0:8000->80/tcp   condescending_cori
25cec84d12ff        nginx               "nginx -g 'daemon ..."   3 minutes ago       Up 3 minutes        80/tcp                 flamboyant_golick
root@hon-vpn:~# 

Now you can access the docker container using

http://server-ip:8000/

I used port 8000 in this cause as i have Apache running on port 80 on the server. If you need to map port 80 and 443, run

docker run -p 80:80 -p 443:443 -d nginx

Volumes

You need will need to share files between server and docker container. This can be done with -v option.

docker run -d -p 8080:80 -v /var/www/html:/usr/share/nginx/html nginx 

Here directory /var/www/html on server is mounted as /usr/share/nginx/html in nginx container.


Posted in Virtualization