Docker Working with Images - gpawade/gpawade.github.io GitHub Wiki
In previous post we saw docker fundamental, how we can use container & images, how we can launch the container in Docker.
In this post we can see the creation of custom images.
This method as much like making a comnmit in a version control system. We create a container, make changes to that container as you would change code, and then commit those changes to a new image.
Let's start
# Creating custom container
$ sudo docker run --name 'my-container' -i -t ubuntu /bin/bash
# install apache into container
root@@57496d97bc0e:/# apt-get -y apache2
root@@57496d97bc0e:/# exit
Now, we save the current state of container, so that we can use that image for launching new apache application. using docker commit command. docker commit <container-id> <new-image-name>
# Commit
$ sudo docoker commit 57496d97bc0e gpawade/apache2
We can also provide the commit message with -m message_text
flag.
We can also provide the tag name with append with colon(:) to image name
Recommended approach for building image is using dockerfile instead of using docker commit
.
The Dockerfile uses instruction for building Docker images.
We can use docker build
command to build the image from the instructions in the Dockerfile.
Let's create the directory and an initial Dockerfile.
$ mkdir web-sample
$ cd web-sample
$ touch Dockerfile
We've created directory to hold the Dockerfile. This directory is build environment/ build context.
Now we can add the instruction in docker file.
FROM ubuntu
RUN apt-get update && apt-get install -y nginx
RUN echo 'Hi, I am running from container' \
>/usr/share/nginx/html/index.html
EXPOSE 80
Now, let's try docker build
command.
$ cd web-sample
$ docker build -t='gpawade/web-sample' .
-t
flag for repository name.
The trailing . tell the docker to look in local directory to find Dockerfile.
Each instruction in Dockerfile add a new layer to image.
# View Image
$ docker images gpawade/web-sample
# Launch new container from image
$ sudo docker run -d -p 80 --name 'web-sample' gpawade/web-sample nginx -g "daemon off;"
Where-
-d
flag - this tell the docker to run detached in the background.
nginx -g "daemon off;"
this will launch Nginx in foreground to run web server.
-p
flag manages which network ports Docker publishes at runtime.
We can see the mapped port to container using following command
$ docker port web-sample 80
0.0.0.0:32769
$ curl localhost:32769
Hi, I am running from container
We can push image to the Docker hub using docker push
commmand.
$ docker push gpawade/web-sample