Run Multiple Containers With Docker Compose | by Arjav Dave | Apr, 2022

Execute a number of containers aspect by aspect with out interfering with one another

docker compose

Docker has gained reputation for a number of causes. One in every of them is creating transportable containers that are quick and simple to deploy.

As talked about on their website: “a container is one thing that packages your code together with some other dependencies in order that it may be deployed throughout a number of platforms reliably”.

These containers may be run domestically in your Home windows, Mac, and Linux. Secondly, main cloud techniques like AWS or Azure do assist them out of the field. Lastly, it may be used on any internet hosting house the place it may be put in and run. If you wish to be taught extra Docker fundamentals and wish a cheat sheet for docker CLI, I wrote an introductory article about it here.

Right here we are going to go deeper to know a number of the superior options like working a number of containers.

With docker-compose one can configure and begin a number of containers with a single YAML file. That is actually useful in case you are engaged on a know-how stack with a number of applied sciences. For instance, in case you are engaged on a mission that requires MySQL database, python for AI/ML, Node.js for real-time processing & .NET for serving API. It might be cumbersome to arrange such an surroundings for every crew member. Docker alleviates this problem with the assistance of compose.

docker compose is a YAML file wherein we are able to configure various kinds of providers. Then with a single command, all containers have been constructed and fired up. There are primarily 3 steps concerned

  • Generate a Dockerfile for every mission.
  • Setup providers in docker-compose.yml file.
  • Fireplace up the containers.

We at the moment are going to implement an answer for the above drawback assertion.

One may count on to have all of the applied sciences put in to run the above-discussed tech stack of MySQL, Python, NodeJS, .NET and PHP. Relatively all you want is a docker engine working. The most recent variations of docker include docker-compose put in. For now, no different set up is required.

Earlier than we begin right here is only a transient of what we’re going to do. We will likely be tackling every know-how one after the other. For every know-how, we are going to create a pattern software (besides MySQL) and create a Dockerfile for every. Then we are going to level this Dockerfile in our docker-compose YAML file. Lastly, we are going to configure docker-compose so that every software does what it’s alleged to do.

Earlier than we get began to create a folder identify super-app. Secondly, create a docker-compose.yml file. On this file, we are going to configure all our functions. So let’s get began!

For these of you interested by code you possibly can go to the repository here.

Set the beneath content material in your docker-compose.yml file.

model: '3.4'
providers:
super-app-db:
picture: mysql:8.0.28
surroundings:
MYSQL_DATABASE: 'super-app'
MYSQL_ROOT_PASSWORD: '$SuperApp1'
ports:
- '3306:3306'
expose:
- '3306'

Underneath the providers part we are going to checklist down all of the sorts of functions to be configured. To begin with we configure a super-app-db service that pulls a docker picture of MySQL with model 8.0.28. Subsequent, we instruct the container to create a database identify super-app with root as default consumer and it’s password set to $SuperApp1.

Lastly, for the reason that default port for MySQL is 3306 we’re mapping it to the containers’ port 3306 and exposing that port for entry.

As soon as the above file is created run the beneath command to get your docker picture created and run it as a container.

docker compose up

MySQL picture will likely be pulled after which the docker will spin up a container to run this picture. MySQL server may be verified by connecting it through a MySQL shopper. If not, fear not, we are going to see beneath how to connect with it through one among our functions. So long as the container will not be deleted the tables will likely be endured.

Let’s configure our subsequent software NodeJS.

We’ll create a quite simple specific node software. So as to take action create a folder named node inside our super-app folder. Add the beneath 3 recordsdata specifically server.js, bundle.json and Dockerfile within the node folder.

server.js:

const server = require("specific")();
server.pay attention(3000, async () => );
server.get("/super-app", async (_, response) =>
response.json( "tremendous": "app" );
);

bundle.json:


"identify": "super-app-node",
"dependencies":
"specific": "^4.17.1"

Dockerfile:

# Obtain the slim model of node
FROM node:17-slim
# Set the work listing to app folder.
# We will likely be copying our code right here
WORKDIR /node
#Copy bundle.json file within the node folder inside container
COPY bundle.json .
# Set up the dependencies within the container
RUN npm set up
# Copy the remainder of the code within the container
COPY . .
# Run the node server with server.js file
CMD ["node", "server.js"]
# Expose the service over PORT 3000
EXPOSE 3000

Right here we’re making a node software that returns JSON after we hit localhost:3000/super-app within the browser. Now, we aren’t straight going to run the mission from this folder.

As a substitute, return to your super-app folder and append the beneath traces to your docker-compose.yml file.

super-app-node:
construct: ./node
ports:
- "3000:3000"

We’re merely mentioning making a service named super-app-node. We’re additionally mapping the container port to the host port 3000. Lastly, run the beneath command to run your two containers i.e. MySQL & NodeJS.

docker compose up

Now when you hit localhost:3000/super-app you will notice a response “tremendous”:”app”. Concurrently your MySQL service can be. Yay! Now we have efficiently created two containers utilizing a docker-compose file.

On to the following software. Let’s create a .NET software that interacts with the database and returns a listing of strings.

We wish the .NET software to attach with the database. Secondly, it can fetch information from the database through a GET API and show it within the browser. To take action create a .NET mission named dotnet inside our super-app mission.

Since writing down all of the steps for creating and organising the mission will likely be fairly prolonged for this weblog and in addition maintain this text centered on docker, a separate article is written on the right way to obtain the above objective.

The article gives step-by-step directions on making a .NET 6 software that connects to MySQL database utilizing EF Core. EF Core is an Object-Relation Mapper to speak between database and code. Notice: Ignore the stipulations part since we have already got a MySQL server working in docker.

.NET App Modifications

Because the tasks will likely be working in their very own containers they’ll’t talk through localhost url. Therefore to ensure that the .NET app to speak with MySQL, the connection string must be up to date. To take action open the appsettings.json and appsettings.Improvement.json recordsdata and substitute localhost with super-app-db for server in DefaultConnection.

Lastly, apps inside containers don’t want HTTPS redirection. Because the HTTPS needs to be dealt with by the server take away the beneath line from Program.cs.

app.UseHttpsRedirection();

Docker

As soon as the mission is ready up and working it’s time to configure it to run inside a docker utilizing Dockerfile and docker-compose. In dotnet folder create Dockerfile with the beneath contents.

#Get the SDK picture to construct and publish the mission
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build-env
WORKDIR /app
# Copy all the pieces
COPY . ./
# Restore as distinct layers
RUN dotnet restore
# Construct and publish a launch
RUN dotnet publish -c Launch -o out
# Construct runtime picture
FROM mcr.microsoft.com/dotnet/aspnet:6.0
WORKDIR /app
#Copy the construct file to the app listing
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "dotnet.dll"]
#Expose the port for communication
EXPOSE 80

Now return to the docker-compose.yml file and append the beneath content material.

super-app-dotnet:
construct: ./dotnet
ports:
- "8080:80"

Right here we’re binding port 8080 of the host machine to the container’s port 80. That’s all for now. Execute the beneath command to fireplace up all of the containers.

docker compose up

Lastly, hit localhost:8080/api/job in a browser. The GET API will fetch the checklist of jobs from the database.

By now, you might need guessed to create a python folder in our super-app folder.

Secondly, create the three recordsdata required for our mission specifically ai-ml.py, necessities.txt and Dockerfile with the beneath contents.

ai-ml.py:

import matplotlib.pyplot as plt
import pandas as pd
from scipy import sign
if __name__ == "__main__":
print("All working good")

necessities.txt:

pandas
scipy
matplotlib

Dockerfile:

# Get the python picture
FROM python:3.7.13-slim
# Change to app listing
WORKDIR /app
# Copy the necessities in to the app
COPY necessities.txt ./
# Set up dependencies
RUN pip set up --no-cache-dir -r necessities.txt
# Copy all the pieces else
COPY . .
#Run the python script
CMD [ "python", "./ai-ml.py" ]

Lastly, return to the docker-compose.yml file and add the beneath content material.

super-app-python:
construct: ./python

It’s so simple as that. Because it’s only a easy script it can run as soon as after which the container will exit. However the logs for the container will present All working nicely printed. That’s all for Python.

Organising PHP with docker is among the best of all. Create two recordsdata index.php and Dockerfile as beneath.

index.php:

<?php echo "I'm working in a container."; ?>

Dockerfile:

# Get the php apache picture
FROM php:8.0-apache
# Change to app listing
WORKDIR /var/www/html
# Copy all the pieces
COPY . .
EXPOSE 80

Lastly, add the beneath content material to docker-compose.yml.

super-app-php:
construct: ./php
ports:
- "8000:80"

Lastly, fireplace up all of the containers once more with docker compose up. If you hit http://localhost:8000 a pleasant message saying “I’m working in a container.” will seem.

Right here is the ultimate repository with all of the Dockerfiles and different setups.

Docker is a superb containerization device and it’s been made extra highly effective with docker-compose. It permits working a number of containers aspect by aspect with out interfering with one another. It needs to be within the arsenal of instruments within the information base.

More Posts