Hello world in Docker

Author
By Darío Rivera
Posted On in Docker

In a previous post, we saw how to install Docker and, at the same time, run the first "hello-world" container. However, this first example might be somewhat confusing for someone just starting with Docker. For this reason, today we will look at a slightly different "Hello World" that better represents the essence of Docker.

In this example, we will use a Dockerfile as it is the most common way you will see in a professional environment to run a Docker container based on an image.

Create the Dockerfile

Every container in docker starts with a Dockerfile which defines what happens inside the container's environment. You must create a folder for this project and within this folder you must create the Dockerfile file and paste the following content in it.

FROM httpd:2.4

COPY ./html/ /usr/local/apache2/htdocs/

As you can see it is extremely simple, the first line of this file tells us that the container will be an instance of the httpd:2.4 image, which comes with apache installed. The third line copies everything we have in the html folder to /usr/local/apache2/htdocs. To make this work correctly you will also need to create the html folder in the project directory. Finally our hello world will go in the index.html file inside this last folder.

mkdir html
echo "<h2>Hello world</h2>" > html/index.html

Create the image

We need to create our own image that will be based of course on httpd as specified in our Dockerfile. To do this, we must run the following command:

docker build --tag=holamundo .

The parameter in --tag refers to the name that will be given to our image.

Run an instance

The last thing that remains is to run an instance of our image, that is, to create a container. For this, we are going to map port 80 of the container to port 8080 of our computer.

docker run -p 8080:80 holamundo

If everything has gone well we could access the URL http://0.0.0.0:8080/ and see a Hello world as a result in the browser.

Finally, I leave you with these two basic docker commands that will help you to know what images and containers exist on your host.

$ docker image ls
REPOSITORY    TAG       IMAGE ID        CREATED           SIZE
holamundo     latest    eb11397e547a    30 minutes ago    154MB
$ docker container ls
CONTAINER ID   IMAGE       COMMAND              CREATED           STATUS           PORTS                  NAMES
f54c000c919d   holamundo   "httpd-foreground"   33 minutes ago    Up 33 minutes    0.0.0.0:8081->80/tcp   hardcore_lamport

Until next time!


Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.