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

How to configure jdk environment under Linux

1. Go to the official website to download the jdk...

JS implements simple calendar effect

This article shares the specific code of JS to ac...

Detailed explanation of the underlying encapsulation of Java connection to MySQL

This article shares the Java connection MySQL und...

Solutions to Files/Folders That Cannot Be Deleted in Linux

Preface Recently our server was attacked by hacke...

MySQL 5.7.23 version installation tutorial and configuration method

It took me three hours to install MySQL myself. E...

Detailed explanation of HTML tables

Function: data display, table application scenari...

Pure CSS to add style to select (no script) implementation

Change the default style of select, usually throug...

Springboot+Vue-Cropper realizes the effect of avatar cutting and uploading

Use the Vue-Cropper component to upload avatars. ...

How to use Vue's idea to encapsulate a Storage

Table of contents background Function Purpose Ide...

MySQL Series 10 MySQL Transaction Isolation to Implement Concurrency Control

Table of contents 1. Concurrent access control 2....

HTML table tag tutorial (34): row span attribute ROWSPAN

In a complex table structure, some cells span mul...

The whole process of configuring hive metadata to MySQL

In the hive installation directory, enter the con...

Web Design Tutorial (8): Web Page Hierarchy and Space Design

<br />Previous article: Web Design Tutorial ...

How to create, start, and stop a Docker container

1. A container is an independently running applic...

Vue Getting Started with Weather Forecast

This article example shares the specific code of ...