Create a Basic Docker Container
Categories:
2 minute read
- Create the working directory in your code editor
- Create a new file called
Dockerfile
and make sure it has no file extension like TXT or YAML and the name is case-sensitive! - Paste the contents from below into the file and save it
FROM ubuntu:latest
RUN apt-get update && apt-get install -y apache2
RUN echo "ServerName localhost" >> /etc/apache2/apache2.conf
COPY index.html /var/www/html/
EXPOSE 80
CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]
Here’s what this Dockerfile does:
FROM ubuntu:latest: This sets the base image for the Docker container as the latest version of Ubuntu.
RUN apt-get update && apt-get install -y apache2: This installs Apache2 web server on the Ubuntu image.
RUN echo “ServerName localhost” » /etc/apache2/apache2.conf: This sets the ServerName as localhost in the Apache configuration file.
COPY index.html /var/www/html/: This copies the index.html file to the default Apache document root directory.
EXPOSE 80: This exposes port 80, which is the default port for Apache web server.
CMD ["/usr/sbin/apache2ctl", “-D”, “FOREGROUND”]: This starts the Apache web server in the foreground, allowing us to see the server logs and interact with it.
- Now create an
index.html
file in the same working directory - Paste the following contents into the file
<!DOCTYPE html>
<html>
<head>
<title>My Docker Apache Server</title>
</head>
<body>
<h1>Hello from Docker container: <?php echo gethostname(); ?></h1>
</body>
</html>
This index.html file uses PHP to display the hostname of the container running the Docker.
- Once you have created the Dockerfile and the index.html file, you can build the Docker image by running the following command in the same directory as the Dockerfile:
docker build -t simple-apache .
- Then you can run the Docker container using the following command which will start the container:
docker run -d -p 8080:80 simple-apache
- This will start the Docker container and map port 8080 of the container to port 80 of the host machine. You can access the Apache web server by opening a web browser and navigating to http://localhost. The web page will display the hostname of the container running the Docker.