Learn to Create a DockerFile & Docker-Compose File

Learn to Create a DockerFile & Docker-Compose File

Docker has become a cornerstone tool in modern development, widely embraced for its containerization benefits. However, the constant stream of commands needed for deploying and managing multiple containers can be a challenging and error-prone endeavor. While deploying and running numerous containers simultaneously is indeed possible, the process demands significant effort and increases the likelihood of mistakes. Let's explore ways to simplify this intricate dance of Docker commands, making container orchestration a more seamless and enjoyable experience.

Step 1: Create a Dockerfile

# Use an official Python runtime as a parent image
FROM python:3.8-slim

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]

Here, we are using a Python image as an example. Adjust it according to your application's requirements.

Step 2: Create a Docker Compose File

Now, let's create a Docker Compose file named docker-compose.yml in the same directory as your Dockerfile.

version: '3'
services:
  web:
    build: .
    ports:
      - "5000:80"

This simple Docker Compose file defines a service named 'web' that builds the image from the current directory and maps port 5000 on the host to port 80 on the container.

Step 3: Run Your Application

To start your application, run the following command in your project directory:

docker-compose up -d

where -d is detaches the services, allowing them to run in the background.

Step 4: Visit the site

Visit http://localhost:5000 in your web browser, and you should see your application running.

Step 5: Stop your docker-compose file

If you want to stop the containers running in background , you can simply write

docker-compose down

as it will stop the containers running.

Conclusion:

You've just created a Docker Compose file to orchestrate your multi-container application effortlessly. ocker Compose simplifies the deployment process and allows you to define your infrastructure as code, making it easy to share and reproduce your development environment.

Happy Coding!

Did you find this article valuable?

Support CodeAryan by becoming a sponsor. Any amount is appreciated!