17. Building a Dockerized Web Application

17. Building a Dockerized Web Application

Understanding Docker and Dockerfile

Docker is a revolutionary tool that simplifies the process of running applications in containers. These containers are self-sufficient, encapsulating everything an application needs to operate seamlessly. At the heart of Docker lies the Dockerfile—a script containing instructions for building a container.

A Dockerfile acts as a recipe, guiding Docker on which base image to use, what commands to execute, and what files to incorporate into the container. Imagine creating a container for a website; the Dockerfile might instruct Docker to utilize an official web server image, copy the website files into the container, and initiate the web server upon container startup.

For a more in-depth understanding of Dockerfile, you can explore further here.

Today's Challenge: Building a Dockerized Web Application

Step 1: Create a Dockerfile

Let's start by crafting a Dockerfile for a simple web application. Whether it's a Node.js or Python app, your Dockerfile will guide the containerization process.

# Use an official base image 
FROM node:14 

# Set the working directory 
WORKDIR /app 

# Copy package.json and package-lock.json 
COPY package*.json ./ 

# Install dependencies 
RUN npm install 

# Copy the application files 
COPY . . 

# Expose the port the app runs on 
EXPOSE 3000 

# Define the command to run your app 
CMD ["npm", "start"]

Step 2: Build and Run the Docker Container

Open your terminal, navigate to the directory containing your Dockerfile and application code, and execute the following commands:

# Build the Docker image 
docker build -t your-image-name . 

# Run the Docker container 
docker run -p 3000:3000 -d your-image-name

Step 3: Verify the Application

Open your web browser and navigate to localhost:3000. If all goes well, you should see your web application up and running.

Step 4: Push to a Repository

Now, let's share your Dockerized masterpiece with the world. Push the Docker image to a public or private repository, such as Docker Hub.

# Log in to Docker Hub (replace with your Docker Hub username) 
docker login 

# Tag your image docker 
tag your-image-name your-dockerhub-username/your-image-name 

# Push the image to Docker Hub
docker push your-dockerhub-username/your-image-name

Thank you for reading this article...

Did you find this article valuable?

Support Explore DevOps by becoming a sponsor. Any amount is appreciated!