# Docker Containerization and Compose

In today's tech-driven environment, effective software deployment and management are critical. [Containerization](https://www.techtarget.com/searchitoperations/feature/Dive-into-the-decades-long-history-of-container-technology) has emerged as a game-changing technology, reducing the time it takes to package and deliver programs. [Docker](https://www.padok.fr/en/blog/container-docker-oci) has taken the lead in transforming the way we write and deliver software with technologies like [Docker](https://www.cio.com/article/247005/what-are-containers-and-why-do-you-need-them.html) [Compose](https://docs.divio.com/reference/docker-docker-compose/) In this blog article, we'll look at [containerization](https://www.coursera.org/projects/containerization-using-docker) and how [Docker](https://info.support.huawei.com/info-finder/encyclopedia/en/Docker+Container.html) and [Docker](https://www.clickittech.com/devops/docker-use-cases/) [Compose](https://www.educative.io/blog/docker-compose-tutorial), work together to ease application deployment and orchestration.

### Introduction

D[ocker](https://www.oracle.com/in/cloud/cloud-native/container-registry/what-is-docker/), a revolutionary technology, revolutionizes software development by offering efficient, scalable, and portable [containerization](https://aws.amazon.com/free/containers/?trk=8b610dcd-92bd-47a0-b523-78ee4f7178b7&sc_channel=ps&ef_id=Cj0KCQjwpc-oBhCGARIsAH6ote9QJAzxFirI3znW6I_67XkJtV4ld5FSwJ2MrtQSDYgReSkoSHxxb_MaAg_LEALw_wcB:G:s&s_kwcid=AL!4422!3!641435066547!p!!g!!container!19256168840!145893961873) platforms like [Docker](https://sematext.com/glossary/docker/) [Compose](https://www.educative.io/answers/docker-compose)

### **What is** [**Docker**](https://www.freecodecamp.org/news/what-is-docker-compose-how-to-use-it/)**?**

[Docker](https://www.knowledgehut.com/blog/devops/docker-vs-container) is an open-source technology that allows developers to automate application deployment in lightweight, portable [containers](https://www.aquasec.com/cloud-native-academy/docker-container/container-advantages/). These [containers](https://www.infoworld.com/article/3310941/why-you-should-use-docker-and-containers.html) bundle a program and all of its dependencies into a single package, guaranteeing consistent behavior across several contexts. [Docker](https://devm.io/docker/containerization-vs-virtualization-docker-introduction-120562) [containers](https://towardsdatascience.com/containerize-your-application-with-docker-b0608557441f) are independent of the host system and may operate on any system that supports [Docker](https://www.linuxjournal.com/content/kubernetes-and-docker-exploring-synergy-containerization), whether it's a developer's laptop, a test server, or a production cluster.

## [Containerization](https://www.geeksforgeeks.org/containerization-using-docker/)

[Containerization](https://www.youtube.com/watch?v=A0g7I4A6GN4&ab_channel=Simplilearn) is the process of combining a program and its dependencies into a single unit known as a [container](https://www.edureka.co/blog/docker-container/). [Containers](https://learn.microsoft.com/en-us/dotnet/architecture/microservices/container-docker-introduction/) are isolated, lightweight, and portable, allowing programs to execute reliably across several environments.

### Understanding [Containerization](https://docs.docker.com/get-started/overview/)

A [containerization](https://www.edureka.co/blog/what-is-docker-container) is a lightweight form of virtualization that allows you to package an application and its dependencies into a single unit known as a [container](https://kodekloud.com/blog/docker-containerization/). [Containers](https://www.freecodecamp.org/news/a-beginner-friendly-introduction-to-containers-vms-and-docker-79a9e3e119b/) are isolated from the host system and ensure consistency across different environments, making it easier to develop and deploy applications.

[Containerization](https://www.edureka.co/blog/what-is-docker-container), as provided by [Docker](https://www.koenig-solutions.com/docker-containerization-essentials-quiz-questions-answers?keyword=&device=c&utm_source=google&utm_medium=cpc&utm_device=c&utm_campaign=P-Max-adgroup-&gclid=Cj0KCQjwpc-oBhCGARIsAH6ote9Y7OV6cglOtnUz1kAKhftb6qWw-QAYFrCv598zHV3gTWLir8sJaYIaAgfrEALw_wcB), is transforming the way we design, distribute, and execute software. Here's why it's so revolutionary:

* **Isolation**
    
* **Portability**
    
* **Efficiency**
    
* **Version Control**
    

**Isolation:** [Containers](https://www.simplilearn.com/tutorials/docker-tutorial/what-is-docker-container) encapsulate a program and its dependencies, guaranteeing constant operation regardless of the underlying infrastructure.

**Portability:** Docker [containers](https://www.ibm.com/topics/docker) are transferable across diverse environments, making local development and deployment easier.

**Efficiency:** Because [containers](https://www.nutanix.com/oneplace/modern-apps?utm_source=google_adwords&utm_medium=paid_search&utm_campaign=Nutanix_Search_APJ_India_MA_CLD_Google_Brand_X_CQ_X_Phrase_Visitors_cpc_English_English_BA_&utm_term=docker%20container&utm_experience=&cq_plac=&cq_net=g&cq_plt=gp&gclid=Cj0KCQjwpc-oBhCGARIsAH6ote__vZhxZhzNJfOYog4z9WMhQEgkzpshE6DkkaMudEzPmDQpBuzLamEaAoi9EALw_wcB) share the same OS kernel, resource overhead is reduced and startup times are reduced.

**Version Control:** [Docker](https://thenewstack.io/containers/) [containers](https://www.codemag.com/Article/2103061/Introduction-to-Containerization-Using-Docker) are versioned, which makes it simple to track changes and revert to prior versions if necessary.

### Key Technology

The most well-known [containerization](https://circleci.com/blog/docker-image-vs-container/) platform is Doc[Docker](https://www.google.com/search?q=docker+Compose&sca_esv=568775834&rlz=1C1VDKB_enIN1061IN1061&sxsrf=AM9HkKkWsjRbuXDemrpPSKL2z1Ml_gyatA%3A1695813450788&ei=Sg8UZfXKL4-useMPtcye-Ak&ved=0ahUKEwj1l9uy1cqBAxUPV2wGHTWmB58Q4dUDCBE&uact=5&oq=docker+Compose&gs_lp=Egxnd3Mtd2l6LXNlcnAiDmRvY2tlciBDb21wb3NlMhAQABiABBgUGIcCGLEDGIMBMgsQABiABBixAxiDATILEAAYgAQYsQMYgwEyCxAAGIAEGLEDGIMBMgsQABiABBixAxiDATIQEAAYgAQYFBiHAhixAxiDATIFEAAYgAQyBRAAGIAEMgsQABiABBixAxiDATIFEAAYgARIqRRQuwVYpRJwAHgCkAEAmAGMAaABsgWqAQM1LjK4AQPIAQD4AQHCAgQQABhHwgIHECMYigUYJ8ICDRAAGIoFGLEDGIMBGEPCAggQABiABBixA8ICBxAAGIoFGEPiAwQYACBBiAYBkAYI&sclient=gws-wiz-serp#ip=1)ker. Docker [containers](https://www.ibm.com/topics/containerization) provide everything required to execute a program, including code, runtime, system libraries, and configuration.

### Example 1: [Containerizing](https://aws.amazon.com/docker/) a web application using Docker

Docker generates a [container](https://linkedin.github.io/school-of-sre/level102/containerization_and_orchestration/containerization_with_docker/) image for web applications requiring Python and PostgreSQL versions, ensuring constant functionality on any machine, regardless of the host environment.

### Step 1: Create the Web Application

A Python web application, using the Flask framework, connects to a PostgreSQL database and displays a list of items on a web page.

```python
mywebapp/
   ├── app.py
   ├── requirements.txt
   └── Dockerfile
```

* **app.py** \- Web application Python code.
    
* Python prerequisites are listed in **requirements.txt**.
    
* [**Dockerfile**](https://www.site24x7.com/learn/containers/how-containers-work.html) - A set of instructions for creating a [Docker](https://docs.docker.com/compose/gettingstarted/) image.
    

### Step 2: Create the Python App (app.py).

```python
from flask import Flask
import psycopg2

app = Flask(__name__)             

# Connect to PostgreSQL database
conn = psycopg2.connect(
    database="mydb",
    user="myuser",
    password="mypassword",
    host="db",
    port="5432"
)

@app.route('/')
def index():
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM items")
    items = cursor.fetchall()
    return '<h1>Items:</h1>' + '<br>'.join([item[1] for item in items])

if __name__ == '__main__':
    app.run(host='0.0.0.0')
```

### Step 3: Make a file called requirements.txt.

List the Python packages on which your application depends in the **requirements.txt file.** In our case, it may contain **Flask** and **psycopg2**

```makefile
Flask==2.1.1
psycopg2-binary==2.9.1
```

### Step 4: Create a [Dockerfile](https://docs.github.com/en/actions/creating-actions/creating-a-docker-container-action) ([Dockerfile](https://www.sdxcentral.com/cloud/containers/definitions/what-is-docker-container/)).

A [Dockerfile](https://geomotiv.com/blog/docker-tutorial-on-real-world-examples/) specifies how to create a [Docker](https://thinkpalm.com/blogs/everything-need-know-docker-adoption-software-containerization/) image for your application. Here's a basic [Dockerfile](https://www.devopsschool.com/blog/docker-explained-what-is-the-advantage-docker-containerization/) for our web application

```dockerfile
# Use the official Python image as the base image
FROM python:3.8

# Set the working directory in the container
WORKDIR /app

# Copy the application code and requirements file into the container
COPY app.py .
COPY requirements.txt .

# Install Python dependencies
RUN pip install -r requirements.txt

# Expose port 5000 for the Flask app
EXPOSE 5000

# Define the command to run when the container starts
CMD ["python", "app.py"]
```

### Step 5: Create a [Docker](https://docs.docker.com/compose/) Image

To construct the [Docker](https://insaid.medium.com/containerization-using-docker-ai-end-to-end-series-part-6-d5d8c0979292) image, go to the directory containing your [Dockerfile](https://docs.docker.com/compose/install/) and execute the following command:

```bash
docker build -t mywebapp .
```

[Docker](https://insaid.medium.com/containerization-using-docker-ai-end-to-end-series-part-6-d5d8c0979292) will create an image called '**<mark>mywebapp</mark>**' with the current directory **('.')** as the build context.

### Step 6: Start the [Docker](https://www.educative.io/blog/beginners-guide-to-docker?psafe_param=1&utm_campaign=brand_educative&utm_source=google&utm_medium=ppc&utm_content=performance_max_india&eid=5082902844932096&utm_term=&utm_campaign=%5BNew%5D+Performance+Max&utm_source=adwords&utm_medium=ppc&hsa_acc=5451446008&hsa_cam=18931439518&hsa_grp=&hsa_ad=&hsa_src=x&hsa_tgt=&hsa_kw=&hsa_mt=&hsa_net=adwords&hsa_ver=3&gclid=Cj0KCQjwpc-oBhCGARIsAH6ote8DCB71N1DA_G-83R9EQYlt5CFTAAzZ48GzamFB3arB-LAViXidEsAaAnOlEALw_wcB) [Container](https://www.cio.com/article/247005/what-are-containers-and-why-do-you-need-them.html)

You may run a [container](https://k21academy.com/docker-kubernetes/what-are-containers/) from the image after it has been built

```bash
docker run -d -p 5000:5000 --name mywebapp-container mywebapp
```

This command launches a [container](https://www.aquasec.com/cloud-native-academy/docker-container/container-advantages/) named '**mywebapp-**[**container**](https://indiaai.gov.in/article/docker-containerization-for-data-scientists)' from the '**mywebapp**' image, mapping port **5000** in the [container](https://www.bmc.com/blogs/what-is-a-container-containerization-explained/) to port **5000** on the host system (**'-p 5000:5000**').

Your web application is now running in a [Docker](https://codeahoy.com/2019/04/12/what-are-containers-a-simple-guide-to-containerization-and-how-docker-works/) [container](https://www.bmc.com/blogs/what-is-a-container-containerization-explained/), with its own Python environment and PostgreSQL database. You may get to it by going to '[http://localhost:5000](http://localhost:5000)' in a web browser.

## [Docker](https://docs.docker.com/compose/compose-file/compose-file-v3/) [Compose](https://www.educative.io/answers/docker-compose)

[Docker](https://docs.docker.com/compose/compose-file/) [Compose](https://k21academy.com/docker-kubernetes/docker-compose/) is a [Docker](https://www.sumologic.com/blog/docker-containers-management/) utility that streamlines the management of multi-[container](https://appsassociates.com/blog/containerization-using-docker/) applications. It defines all of your application stack's services, networks, and volumes in a YAML file.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><a target="_blank" rel="noopener noreferrer nofollow" href="https://github.com/docker/compose" style="pointer-events: none">Docker</a> <a target="_blank" rel="noopener noreferrer nofollow" href="https://docs.linuxserver.io/general/docker-compose" style="pointer-events: none">Compose</a> is especially beneficial in development and testing settings where complicated applications with several components must be swiftly spun up.</div>
</div>

###   
Example 2: The project involves creating a web application with a React front-end, Node.js back-end API, and a PostgreSQL database.

Assume you're working on a web application that includes a React front-end, a Node.js back-end API, and a PostgreSQL database. You may specify these components in a '[**docker**](https://www.tutorialspoint.com/docker/docker_compose.htm)**\-**[**compose**](https://caprover.com/docs/docker-compose.html)**.yml**' file with [Docker](https://github.com/docker/compose) [Compose](https://webdock.io/en/docs/how-guides/docker-guides/how-to-install-and-run-docker-containers-using-docker-compose). When you execute '[**docker**](https://www.baeldung.com/ops/docker-compose)**\-**[**compose**](https://www.linode.com/docs/guides/how-to-use-docker-compose/) **up**,' it creates and manages [containers](https://www.padok.fr/en/blog/container-docker-oci) for each component of your application, ensuring that they can interact with one another.

### Step 1: Create a directory

```scss
mywebapp/
   ├── frontend/
   │     ├── Dockerfile
   │     └── (React frontend files)
   ├── backend/
   │     ├── Dockerfile
   │     └── (Node.js backend files)
   ├── docker-compose.yml
   └── database/
         └── (PostgreSQL data files)
```

* The React front-end files are located in the '**frontend**' directory.
    
* The Node.js backend files are located in the '**backend'** directory.
    
* PostgreSQL's data files will be stored in the '**database**' directory.
    
* Each '[**Dockerfile**](https://www.simplilearn.com/tutorials/docker-tutorial/docker-compose)' provides instructions for creating [Docker](https://weaviate.io/developers/weaviate/installation/docker-compose) images for the front and back ends of the services.
    

### **Step 2: Create** [**Dockerfiles**](https://pypi.org/project/docker-compose/)

### `Dockerfile` for the React frontend

```dockerfile
# Use the official Node.js image as the base image
FROM node:14

# Set the working directory in the container
WORKDIR /app/frontend

# Copy the frontend files into the container
COPY ./frontend .

# Install dependencies and build the React app
RUN npm install
RUN npm run build

# Expose port 80 for the React app
EXPOSE 80

# Command to start the React app
CMD ["npm", "start"]
```

### [`Dockerfile`](https://code.visualstudio.com/docs/containers/docker-compose) for the Node.js backend

```dockerfile
# Use the official Node.js image as the base image
FROM node:14

# Set the working directory in the container
WORKDIR /app/backend

# Copy the backend files into the container
COPY ./backend .

# Install dependencies for the backend
RUN npm install

# Expose port 3000 for the Node.js app
EXPOSE 3000

# Command to start the Node.js app
CMD ["npm", "start"]
```

### Step 3: Create the [docker](https://www.xenonstack.com/blog/docker-container)\-[compose](https://www.knowledgehut.com/blog/devops/docker-compose).yml file.

To specify the services and their configurations, create a [**docker**](https://itnext.io/getting-started-with-docker-1-b4dc83e64389)**\-**[**compose**](https://docs.ansible.com/ansible/latest/collections/community/docker/docker_compose_module.html)**.yml** file at the root of your project:

```yaml
version: '3'
services:
  frontend:
    build:
      context: .
      dockerfile: frontend/Dockerfile
    ports:
      - "80:80"

  backend:
    build:
      context: .
      dockerfile: backend/Dockerfile
    ports:
      - "3000:3000"
    depends_on:
      - database

  database:
    image: postgres:latest
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword
      POSTGRES_DB: mydb
```

* We distinguish three types of services: frontend, backend, and database.
    
* The [Dockerfile](https://k21academy.com/docker-kubernetes/what-are-containers/) for each service is specified in the build section.
    
* External access is granted through port 80 for the React app and port 3000 for the Node.js app.
    
* The **depends\_on** option guarantees that the backend service only begins after the database service has been started.
    
    ### Step 4: Execute [Docker](https://cloud.google.com/architecture/best-practices-for-building-containers) [Compose](https://circleci.com/docs/docker-compose/).
    
* Navigate to the directory where your [docker](https://middleware.io/blog/understanding-the-docker-ecosystem/)\-[compose](https://www.linode.com/docs/guides/how-to-use-docker-compose/).yml file is located and run the following command
    

```yaml
docker-compose up
```

[Docker](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-compose-on-ubuntu-20-04) [Compose](https://devhints.io/docker-compose) will construct [Docker](https://www.atlassian.com/microservices/microservices-architecture/kubernetes-vs-docker) images for your front-end and back-end services, as well as [containers](https://www.cio.com/article/247005/what-are-containers-and-why-do-you-need-them.html) and start them. In addition, it will create a PostgreSQL [container](https://hackernoon.com/docker-containerization-the-ultimate-guide) for your database.

Your React front-end, Node.js back-end, and PostgreSQL database are now operating in different [containers](https://www.infoworld.com/article/3310941/why-you-should-use-docker-and-containers.html), and [Docker](https://developer.adobe.com/commerce/cloud-tools/docker/containers/) [Compose](https://medium.com/clarusway/how-can-we-easily-and-visually-explain-the-docker-compose-53df77e9f046) guarantees that they can interact as configured in the **<mark>docker-</mark>**[**<mark>compose</mark>**](https://dockerlabs.collabnix.com/intermediate/docker-compose/)**<mark>.yml file.</mark>**

[Docker](https://openliberty.io/guides/containerize.html) [Compose](https://www.youtube.com/watch?v=HG6yIjZapSA&ab_channel=ProgrammingwithMosh) simplifies managing complex multi-[container](https://www.vultr.com/docs/how-to-use-docker-creating-your-first-docker-container/?utm_source=performance-max-apac&utm_medium=paidmedia&obility_id=16876059738&utm_adgroup=&utm_campaign=&utm_term=&utm_content=&gclid=Cj0KCQjwpc-oBhCGARIsAH6ote9ieeZuJmVOWx9AroZNkBj_l55cfGUEOuCKC9YfNmisfXTiI5U8AEgaAhEfEALw_wcB) systems by describing services and dependencies in a single configuration file, enabling communication with the PostgreSQL database during development and testing.

Your React front-end can be found at [http://localhost](http://localhost), and your Node.js back-end can be found at [http://localhost:3000](http://localhost:3000).

<details data-node-type="hn-details-summary"><summary>Summary</summary><div data-type="detailsContent"><a target="_blank" rel="noopener noreferrer nofollow" href="https://en.wikipedia.org/wiki/Docker_(software)" style="pointer-events: none">Containerization</a> is a technology for packaging, distributing, and running applications in isolated environments, with <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.geeksforgeeks.org/docker-compose/" style="pointer-events: none">Docker</a> being a key platform. <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.statista.com/topics/8299/container-technology/?kw=&amp;crmtag=adwords&amp;gclid=Cj0KCQjwpc-oBhCGARIsAH6ote8Cr_7c8R7kdpylkAdz7lYOYgoNtamZhRMgs3lzHErhopa85XjahakaAtywEALw_wcB" style="pointer-events: none">Docker</a> <a target="_blank" rel="noopener noreferrer nofollow" href="https://java.testcontainers.org/modules/docker_compose/" style="pointer-events: none">Compose</a> is a <a target="_blank" rel="noopener noreferrer nofollow" href="https://avinetworks.com/glossary/container-deployment/" style="pointer-events: none">Docker</a> tool for managing multi-<a target="_blank" rel="noopener noreferrer nofollow" href="https://www.upgrad.com/blog/what-is-docker-container/" style="pointer-events: none">container</a> applications, simplifying the setup process by defining essential services and dependencies in a single configuration file.</div></details>

Stay tuned for the upcoming articles in the series, where we'll discuss more interesting topics related to [Docker](https://docs.appsmith.com/getting-started/setup/installation-guides/docker). Subscribe to our channel to ensure you don't miss any part of this enlightening journey!

Thank you for reading our blog. Our top priority is your success and satisfaction. We are ready to assist with any questions or additional help.

Warm regards,

[**Kamilla Preeti Samuel,**](https://www.linkedin.com/in/preeti-samuel-kamilla-5a247962/)

**Content Editor**

[**ByteScrum Technologies Private Limited!**](https://www.bytescrum.com/) 🙏
