Detailed explanation of the Sidecar mode in Docker Compose

Detailed explanation of the Sidecar mode in Docker Compose

What is Docker Compose

In today's world where microservices are prevalent, we usually define Compose as an orchestration tool for unified startup and shutdown of containers.

But I still have a question before, who would use Compose to deploy multiple services on a single server? Just use a single service! Until I encountered the following requirement, I realized that when I had to use multiple services on a server, Compose could use the sidecar mode to make it easy for a service to call another service through 127.0.0.1

Requirements encounter inappropriate language

A project developed in golang hopes to print the student status based on the student information. Part of the student status table is as follows

It's not that there is no library for operating words in Go, but it is still very difficult to operate such a complex word and fill in the information. So we came up with a solution.

Implementation

1. Define a same template through Excel

2. Golang fills the value in the specified cell of Excel, which is much simpler than filling the value in Word. Part of the code

xlsx.SetCellValue("Sheet1", "C3", student.Major.Name)
xlsx.SetCellValue("Sheet1", "F3", student.ClassInfo.Name)
xlsx.SetCellValue("Sheet1", "J3", student.SchoolSystem)
 
xlsx.SetCellValue("Sheet1", "B4", student.Name)
xlsx.SetCellValue("Sheet1", "D4", student.BeforName)
xlsx.SetCellValue("Sheet1", "F4", student.Gender)
xlsx.SetCellValue("Sheet1", "H4", student.Nation)
 
xlsx.SetCellValue("Sheet1", "B5", student.IdCardNo)
xlsx.SetCellValue("Sheet1", "F5", student.HomePlace)
 
xlsx.SetCellValue("Sheet1", "B6", student.Birthday.Format("20060102"))
xlsx.SetCellValue("Sheet1", "D6", student.EntranceTime.Format("20060102"))
xlsx.SetCellValue("Sheet1", "F6", student.JoinTeamTime)
 
xlsx.SetCellValue("Sheet1", "B7", student.FamilyAddress)
xlsx.SetCellValue("Sheet1", "F7", student.HealthStatus)

3. The most critical step is to convert Excel into PDF and return it to the front end for display or printing

I didn't find a golang library for converting excel to pdf on github (please leave a message if you have any recommendations), so I thought of the FreeSpire.Xls library in .net, which can easily realize the function of converting excel to pdf. So I need a .net api to convert the excel generated and filled in go to pdf, so I created a .net webapi, defined the project name as pdfprocessor, and defined a Controller

[Route("[controller]")]
    public class PDFController : ControllerBase
    {
        private readonly ILogger<PDFController> _logger;
        public PDFController(ILogger<PDFController> logger)
        {
            _logger = logger;
        }

        [HttpPost]
        public async Task<IActionResult> HttpPostAsync()
        {
            try
            {
                Stream stream = Request.Body;
                byte[] buffer = new byte[Request.ContentLength.Value];
                stream.Position = 0L;
                stream.ReadAsync(buffer, 0, buffer.Length);
                Workbook wb = new Workbook();
                wb.LoadFromStream(stream);
                Worksheet ws = wb.Worksheets[0];
                var streamReturn = new MemoryStream();

                ws.SaveToPdfStream(streamReturn);
                return File(streamReturn, "application/octet-stream");
            }
            catch (Exception ex)
            {
                _logger.LogError("", ex);
                return BadRequest(ex.Message);
            }
        }
    }

4. Deploy the go project and the .net project, so that the go language calls the .net api to convert excel to pdf

Because this is a small single project, I need to consider how to make the deployment and call relatively simple. At this time, I thought of Docker Compose.

I can start the go api and .net api at the same time through docker-compose. The most important thing is that the go and .net projects can use the same network, so that the go api can call the .net api through 127.0.0.1:port. The topology is as follows

5. The go api calls the .net api through 127.0.0.1, so that the .net api becomes a sidecar of the go api and serves it

response, err := http.Post("http://127.0.0.1:6081/PDF", "multipart/form-data;boundary="+multipart.NewWriter(bytes.NewBufferString("")).Boundary(), bytes.NewReader(byteA))
if err != nil {
    c.Bad(err.Error())
    return
}
defer response.Body.Close()
if response.StatusCode != 200 {
    data, _ := ioutil.ReadAll(response.Body)
    c.Bad(string(data))
    return
}
 
pdfFilePth := fmt.Sprintf("./templates/tmp/%s.pdf", uuid.New())
f, err := os.Create(pdfFilePth)
if err != nil {
    c.Bad(err.Error())
    return
}
io.Copy(f, response.Body)
c.Ctx.Output.Download(pdfFilePth, "data.xlsx")

6. docker-compose deployment

Writing a Dockerfile for Go

FROM library/golang
 
WORKDIR /app
RUN go env -w GO111MODULE=on
RUN go env -w GOPROXY=https://goproxy.cn,direct
ADD api/ /app
RUN cd /app
RUN go mod tidy
RUN go build main.go
ENTRYPOINT ["/app/main"]
EXPOSE 6080

Writing .net Dockerfile

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
RUN apt-get update
RUN apt-get install -y --no-install-recommends libgdiplus libc6-dev 
RUN apt-get install -y fontconfig xfonts-utils
COPY /pdfprocessor/fonts/ /usr/share/fonts/
RUN mkfontscale
RUN mkfontdir
RUN fc-cache -fv

WORKDIR /app
EXPOSE 6081

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["pdfprocessor/pdfprocessor.csproj", "pdfprocessor/"]
RUN dotnet restore "pdfprocessor/pdfprocessor.csproj"
COPY . .
WORKDIR "/src/pdfprocessor"
RUN dotnet build "pdfprocessor.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "pdfprocessor.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "pdfprocessor.dll"]

Write docker-compose.yaml to let goapi and .net api use the same network

version: '3.4'

services:
  pdfprocessor:
    image: pdfprocessor
    build:
      context: .
      dockerfile: pdfprocessor/Dockerfile
    depends_on:
      - eduadmin
    network_mode: "service:eduadmin"
  eduadmin:
    image: eduadmin
    build:
      context: .
      dockerfile: api/Dockerfile
    ports:
      - "6080:6080"
      - "6088:6088"

7. Start the service through docker-compose up -d and view the PDF display effect

Finally, I want to say that docker-compose is really great!

This is the end of this article about the Sidecar mode of Docker Compose. For more information about the Sidecar mode of Docker Compose, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief discussion on how to solve the depends_on order problem in Docker-compose
  • Practical notes on installing Jenkins with docker-compose
  • Detailed process of getting started with docker compose helloworld
  • Docker Compose installation and usage steps

<<:  A brief discussion on HTML special character encoding CSS3 content: "I am a special symbol"

>>:  Comment reply pop-up mask effect implementation idea compatible with ie 8/chrome/firefox

Recommend

N ways to achieve two-column layout with CSS

1. What is a two-column layout? There are two typ...

How to prevent computer slowdown when WIN10 has multiple databases installed

Enable the service when you need it, and disable ...

Detailed tutorial on how to install MySQL 5.7.18 in Linux (CentOS 7) using YUM

The project needs to use MySQL. Since I had alway...

How to run .sh files in Linux system

There are two ways to run .sh files in Linux syst...

Detailed steps to install the specified version of docker (1.12.6) using rpm

1. Reasons If the system is Centos7.3, the Docker...

MySQL 8.0.19 installation detailed tutorial (windows 64 bit)

Table of contents Initialize MySQL Install MySQL ...

Vue simple implementation of turntable lottery

This article shares the specific code of Vue to s...

Detailed explanation of GaussDB for MySQL performance optimization

Table of contents background Inspiration comes fr...

MySQL 20 high-performance architecture design principles (worth collecting)

Open Source Database Architecture Design Principl...

MySQL replication mechanism principle explanation

Background Replication is a complete copy of data...

Docker and portainer configuration methods under Linux

1. Install and use Docer CE This article takes Ce...

How to reset the root password in mysql8.0.12

After installing the database, if you accidentall...

Rhit efficient visualization Nginx log viewing tool

Table of contents Introduction Install Display Fi...