How can I build a docker file, especially an image?

80    Asked by ColemanGarvin in Devops , Asked on Jul 4, 2024

 I am currently in a particular task which is related to creating a lightweight docker image for a particular Go application. Explain to me how can I use the multi-stage builds in my docker files to achieve a smaller final image and Describe to me the steps that should I take to build this particular image. 

Answered by Diya tomar

 In the context of DevOps, here are the steps given for how you can create a lightweight docker image for a particular Go application:-

Creating the dockerfile

This can be done by using the two stages. The first stage would be used for building the application and the second one would be used for the production of a minimal final image. The first stage uses a full development, on the other hand, the second stage would use a minimal base image such as “alpine” to reduce the size.

Writing the dockerfile

# Stage 1: Build Stage
FROM golang:1.18 AS builder
# Set the Current Working Directory inside the container
WORKDIR /app
# Copy go mod and sum files
COPY go.mod go.sum ./
# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download
# Copy the source from the current directory to the working Directory inside the container

COPY . .

# Build the Go app
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /go/bin/app
# Stage 2: Run Stage
FROM alpine:latest
# Copy the Pre-built binary file from the previous stage
COPY –from=builder /go/bin/app /app/app
# Expose port 8080 to the outside world
EXPOSE 8080
# Command to run the executable
ENTRYPOINT [“/app/app”]
Building the docker image
“docker build -t go app:latest”

Here is the approach given by using Java programming language of how you can create a lightweight docker image for a Java-based application by using multi-stage builds:

# Stage 1: Build Stage
FROM maven:3.8.6-openjdk-17-slim AS builder
# Set the working directory
WORKDIR /app
# Copy the pom.xml and download the dependencies
COPY pom.xml .
RUN mvn dependency:go-offline
# Copy the source code
COPY src ./src
# Package the application
RUN mvn clean package
# Stage 2: Run Stage
FROM openjdk:17-jdk-alpine
# Set the working directory
WORKDIR /app
# Copy the JAR file from the build stage
COPY –from=builder /app/target/*.jar app.jar
# Expose the application port

EXPOSE 8080

# Run the application
ENTRYPOINT [“java”, “-jar”, “app.jar”]


Your Answer

Interviews

Parent Categories