Create a Basic Docker Container

This lab will set up an Apache web server with a basic index file that displays the computer name of the container running the Docker.
  1. Create the working directory in your code editor
  2. Create a new file called Dockerfile and make sure it has no file extension like TXT or YAML and the name is case-sensitive!
  3. 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.

  1. Now create an index.html file in the same working directory
  2. 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.

  1. 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 .
  1. Then you can run the Docker container using the following command which will start the container:
docker run -d -p 8080:80 simple-apache
  1. 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.
Last modified July 21, 2024: update (e2ae86c)