By default, when we deploy a container using an image, the container is supposed to have all files required to run, and do its job. Let us take an example of a basic appache server running on CentOS.
The process that can be used to bring up this container can be to create a Dockerfile that will create container with base CentOS and install httpd server. The content of the file can be as below:
==== ===
[root@gw20-lap-doc1 attach_ext_vol]# cat Dockerfile
FROM centos
RUN yum -y install httpd
ENTRYPOINT [“/usr/sbin/httpd”, “-D”, “FOREGROUND”]
==== ===
Let us assume the name of the image that is build from this Dockerfile is myhttpd.
Running the following command will bring the container:
[root@gw20-lap-doc1 sandbox]# docker run -p 80:80 myhttpd
You may access the web page by accessing the url of the node hosting the container. However, you will notice that the webpage displayed is the default Appache server’s page.
What can be dome to display is a customized web page that displays “Hello to my page” ?
You will require an index.html file in /var/www/html folder in the container.
One way is to create an index.html file in the node hosting the container and copying it when building the image, so that it adds the file when the container comes up, or the other way is to ensure the container can refer to an index.html file that is in the node hosting the container.
Once you have the index.html file in the node hosting the container, start the image myhttpd by running the following command:
[root@gw20-lap-doc1 sandbox]# docker run -v $(pwd):/var/www/html/ -p 80:80 myhttpd
Or
[root@gw20-lap-doc1 sandbox]# docker run -v -v /Sandbox/html:/var/www/html/ -p 80:80 myhttpd
When running this command, if the server in the container searches for any file in /var/www/html , it will refer to a file with the exact name it is searching for, in the directory from where the run command is executed.
A twist !!
Imagine a scenario, where you have a new docker image that had three folders in /var/www/html, and the same three folders in the node hosting the container too.
- dir1
- dir2
- dir3
Now you wanted to start the container using the image. However, you want the container to refer dir1 and dir2 from the local server, and use the dir3 from the copy in the container itself. Here you are planning to change contents of dir1 and dir2 hosted in the local server often, and the updated files should be used by the container. The command to use is:
[root@gw20-lap-doc1 sandbox]# docker run -v /var/www/html/dir3 -v $(pwd):/var/www/html/ -p 80:80 myhttpd
How to run it using Docker Compose file ?
The below docker-compose.yml can be used to run the same container with the attachments
[root@gw20-lap-doc1 sandbox]# cat docker-compose.yml
version: ‘3’
services:
myhttpdserver:
build: .
ports:
– “80:80”
volumes:
– .:/var/www/html