Containerize a Web Application
1Create a project directory
mkdir ami-docker cd ami-docker
2Create a simple web page
Create a file named my-index.html with the following code.
<!DOCTYPE html>
<html>
<head>
<title>Ami's First Docker App</title>
</head>
<body style="font-family: Arial, sans-serif; text-align: center; margin-top: 50px;">
<h1>Hello from inside a Docker Container!</h1>
<p>Running locally on localhost.</p>
</body>
</html>3Create a Dockerfile
A Dockerfile contains instructions on how Docker should build your custom image. Create a file named Dockerfile (no file extension) in the same directory.
# Use the official Ubuntu image FROM ubuntu:latest # Copy your webpage into html public folder COPY my-index.html /var/www/html/ # Expose port 80 to the outside world EXPOSE 80 # Install Apache (Build Phase) RUN apt-get update && \ apt-get install -y apache2 && \ rm -rf /var/lib/apt/lists/* # Start Apache in the foreground (Runtime Phase) CMD ["apache2ctl", "-D", "FOREGROUND"]
4Build the Docker image
Run this in the terminal where the Dockerfile is located.
docker build -t ubuntu .
5Run and test on localhost
docker run -d -p 7070:80 --name web-container ubuntu
6Check the container status is Up
docker ps
web-container with status Up and ports 0.0.0.0:7070->80/tcp.7Connect to the container’s shell
docker exec -it web-container bash
8Test in the browser
Open a web browser on your host machine and navigate to:
http://localhost:7070/my-index.html
Save Container Image
If you make changes inside a running container, commit its current state into a new local image so you don’t lose your work. This is handy for learning; for repeatable projects, prefer updating the Dockerfile and rebuilding.
1Check current container name and status
docker ps
2Save the image with the required name
Syntax:
docker commit <running_container_name_or_id> ubuntu-apache-installed
Example:
docker commit web-container ubuntu-apache-installed
3Verify
Run docker images. You should see ubuntu-apache-installed listed in your local images.
docker images
Mount Local Drive to the Container
1Run a new container with the local directory mounted
docker run -d -p 7070:80 -v /Users/amitb/ami-docker:/var/www/html --name ubuntu-mount ubuntu-apache-installed sleep infinity
Then run docker ps and verify the status shows Up and the PORTS column maps 7070->80.
/Users/amitb/ami-docker with the path to your own project folder.2Start Apache inside the new container
The container runs sleep infinity, so Apache needs to be started manually.
docker exec -it ubuntu-mount service apache2 start
3Test in your browser
Navigate to:
http://localhost:7070
Dockerfile, my-index.html), served by Apache on port 7070.