DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Software Design and Architecture
  3. Containers
  4. How To Use Linux Containers

How To Use Linux Containers

In this article, we will provide a step-by-step guide to building Linux containers with applications intended for Cloud deployment

Dmitry Chuyko user avatar by
Dmitry Chuyko
·
Mar. 06, 23 · Tutorial
Like (2)
Save
Tweet
Share
7.26K Views

Join the DZone community and get the full member experience.

Join For Free

Linux containers are a powerful solution for:

  • Software standardization
  • Acceleration of development and testing
  • Effective resource management throughout the whole lifecycle of an application

Here, we will provide a step-by-step guide to building Linux containers with applications intended for Cloud deployment. As an example, we will use BellSoft’s open-source Alpaquita Stream containers hosted on the Docker Hub Container Image Library.

To complete the guide, you must have the docker daemon installed and running. We will explain how to pull a selected container image from the repository and run it with Java, Python, GCC-based applications, and native images. You can use your own app or create a sample project, as shown below.

Linux Containers for Java Applications

Pull a Docker Image

To create a container, run:

$ docker image pull docker bellsoft/<repository>:<image_tag>

Start the container with:

$ docker run -it --rm bellsoft/<repository>:<image_tag>

Alternatively, utilize a combined command:

$ docker container run --rm -it bellsoft/<repository>:<image_tag>

Suppose you have chosen a Liberica Runtime Container, which includes musl-based Alpaquita Stream (a glibc-based option is also available) and Liberica JDK Lite 11. The command will be as follows: 

$ docker container run --rm -it bellsoft/liberica-runtime-container:jdk-11.0.17-musl

Note that pulling an image is not obligatory but recommended if you don’t want to pull an image every time you repeat the build process. 

Write a Dockerfile and Run the App

By using a JRE image instead of a full JDK to run a Java application, you will reduce the container size by approx. 50%.

So, in the Dockerfile for our application, we will specify two images — one for building an app and another for running it. We will use a standard Spring Petclinic project as a sample.

Write the following Dockerfile:

Dockerfile
 
FROM bellsoft/liberica-runtime-container:jdk-17-stream-musl as builder

WORKDIR /home/myapp

RUN apk add git

RUN git clone https://github.com/spring-projects/spring-petclinic.git

RUN cd spring-petclinic && ./mvnw package

FROM bellsoft/liberica-runtime-container:jre-17-stream-musl

WORKDIR /home/myapp

COPY --from=builder /home/myapp/spring-petclinic/target .

CMD ["java", "-jar", "spring-petclinic-3.0.0-SNAPSHOT.jar"]


Build the app image:

$ docker build --progress plain -t javaappimage .

Now, run the image:

docker run  -p 8080:8080 javaappimage

Done! Open the browser to access the Petclinic application.

Linux Containers for Native Image

Pull a Docker Image

We provide images with Liberica Native Image Kit (NIK), an open-source GraalVM-based utility for converting JVM applications into native executables. Developers who work with native images or consider integrating the technology into their project can pull the following image:

$ docker container run --rm -it bellsoft/liberica-native-image-kit-container:jdk-11-nik-21.3.3-stream-musl

Or any image you deem appropriate depending on the JDK and NIK version and libc implementation (BellSoft’s optimized musl or glibc).

Create a Native Image

First, let’s write a simple application to be converted into a native executable. Alternatively, use your own project.

Java
 
public class Example {

    public static void main(String[] args) {

        String str = "Native Image is awesome";

        String reversed = reverseString(str);

        System.out.println("The reversed string is: " + reversed);

    }

    public static String reverseString(String str) {

        if (str.isEmpty())

            return str;

        return reverseString(str.substring(1)) + str.charAt(0);

    }

}


The Dockerfile must contain the following information:

Dockerfile
 
FROM bellsoft/liberica-native-image-kit-container:jdk-11-nik-21.3.3-stream-musl

WORKDIR /home/myapp

COPY Example.java /home/myapp

RUN javac Example.java

RUN native-image Example

FROM bellsoft/alpaquita-linux-base:stream-musl

WORKDIR /home/myapp

COPY --from=0 /home/myapp/example.

CMD ["./example"] 


Go to the application directory and run:

$ docker build.

Below is the process of building the image:

Dockerfile
 
[+] Building 370.9s (14/14) FINISHED

 => [internal] load build definition from Dockerfile                                                                                   0.1s

 => => transferring dockerfile: 357B                                                                                                   0.0s

 => [internal] load .dockerignore                                                                                                      0.0s

 => => transferring context: 2B                                                                                                        0.0s

 => [internal] load metadata for docker.io/bellsoft/alpaquita-linux-base:stream-musl                                                   0.0s

 => [internal] load metadata for docker.io/bellsoft/liberica-native-image-kit-container:jdk-11-nik-21.3.3-stream-musl                  4.8s

 => [internal] load build context                                                                                                      0.1s

 => => transferring context: 454B                                                                                                      0.0s

 => [stage-1 1/3] FROM docker.io/bellsoft/alpaquita-linux-base:stream-musl                                                             0.1s

 => [stage-0 1/5] FROM docker.io/bellsoft/liberica-native-image-kit-container:jdk-11-nik-21.3.3-stream-musl@sha256:3c5a09abb2559cf0  293.4s

 => => resolve docker.io/bellsoft/liberica-native-image-kit-container:jdk-11-nik-21.3.3-stream-musl@sha256:3c5a09abb2559cf04e7527b81b  0.0s

 => => sha256:3c5a09abb2559cf04e7527b81bfa123ca52592ef2bce1512d837fbd0336440e9 951B / 951B                                             0.0s

 => => sha256:79998423fd609bb42881f8eb6721aa22451cdb46363b4fc5f49fc50390759138 2.72kB / 2.72kB                                         0.0s

 => => sha256:4f4293381c77f4d905cfa2034b4fe3adff4515508d08b0093a8db16728ba4879 3.34MB / 3.34MB                                         7.1s

 => => sha256:c3263c13b6f5c1ba5a386dc02047af54fdeefc8a92538ffc973915cdb0de9881 532.42kB / 532.42kB                                     7.0s

 => => sha256:f6c678d36153293dc6b01a73696b4ef60a9ecb44e62da72fd96b31e679f1ed2d 323.95MB / 323.95MB                                   284.4s

 => => extracting sha256:4f4293381c77f4d905cfa2034b4fe3adff4515508d08b0093a8db16728ba4879                                              0.1s

 => => extracting sha256:c3263c13b6f5c1ba5a386dc02047af54fdeefc8a92538ffc973915cdb0de9881                                              0.0s

 => => extracting sha256:f6c678d36153293dc6b01a73696b4ef60a9ecb44e62da72fd96b31e679f1ed2d                                              8.8s

 => [stage-1 2/3] WORKDIR /home/myapp                                                                                                  0.0s

 => [stage-0 2/5] WORKDIR /home/myapp                                                                                                  0.5s

 => [stage-0 3/5] COPY Example.java /home/myapp                                                                                        0.0s

 => [stage-0 4/5] RUN javac Example.java                                                                                               1.0s

 => [stage-0 5/5] RUN native-image Example                                                                                            70.6s

 => [stage-1 3/3] COPY --from=0 /home/myapp/example .                                                                                  0.1s

 => exporting to image                                                                                                                 0.1s

 => => exporting layers                                                                                                                0.1s

 => => writing image sha256:f03df73515790f3ffe210fc139d5a0752c088fd242f571e19d111377f7703c6a                                           0.0s


Verify the image was created.

Dockerfile
 
$ docker images

REPOSITORY     TAG            IMAGE ID       CREATED              SIZE

<none>         <none>         f03df7351579   About a minute ago   19MB


Tag the newly built image with a meaningful name.

Dockerfile
 
$ docker tag f03df7351579 bellsoft-nik:example-musl

$ docker run -it --rm f03df7351579

The reversed string is: emosewa si egamI evitaN


Linux Containers for Python

BellSoft provides Alpaquita Linux images with Python 3.10 and basic Python utilities (pip, setuptools, wheel). Two libc options (BellSoft’s musl perf and glibc) are available.

First, let’s write a simple flask application:

Dockerfile
 
$ cat requirements.txt

flask

markup

jinja2

$ cat test.py

from flask import Flask

app = Flask(__name__)

@app.route('/')

def hello_world():

    return 'Hello, Docker!'


Now, write a Dockerfile with the following contents:

Dockerfile
 
FROM bellsoft/alpaquita-linux-python:3.10-stream-musl

WORKDIR /myapp

COPY requirements.txt .

RUN pip3 install -r requirements.txt

COPY test.py .

ENV PATH=/root/.local:$PATH

CMD ["python3", "-m" , "flask", "--app", "./test.py", "run", "--host=0.0.0.0"]


Finally, build a Docker image with this Dockerfile:

$ docker build -t flaskimage .

The process of  building an image will start:

Dockerfile
 
[+] Building 1.3s (10/10) FINISHED

 => [internal] load build definition from Dockerfile                                                                                   0.0s

 => => transferring dockerfile: 38B                                                                                                    0.0s

 => [internal] load .dockerignore                                                                                                      0.0s

 => => transferring context: 2B                                                                                                        0.0s

 => [internal] load metadata for docker.io/bellsoft/alpaquita-linux-python:3.10-stream-musl                                            1.2s

 => [internal] load build context                                                                                                      0.0s

 => => transferring context: 63B                                                                                                       0.0s

 => [1/5] FROM docker.io/bellsoft/alpaquita-linux-python:3.10-stream-musl@sha256:2d5656810f19f028b5992cbfcdd3e833cfb1839b5b6078b5a2a1  0.0s

 => CACHED [2/5] WORKDIR /myapp                                                                                                        0.0s

 => CACHED [3/5] COPY requirements.txt .                                                                                               0.0s

 => CACHED [4/5] RUN pip3 install -r requirements.txt                                                                                  0.0s

 => CACHED [5/5] COPY test.py .                                                                                                        0.0s

 => exporting to image                                                                                                                 0.0s

 => => exporting layers                                                                                                                0.0s

 => => writing image sha256:9f9335b2d7339a656e1b860e0d0d293c528e06aa21d0be41ee46b67fbb9e9f12                                           0.0s

 => => naming to docker.io/library/flaskimage                                                                                          0.0s


You can now run your Python application in Docker:

Dockerfile
 
$ docker run -d -p 6000:5000 flaskimage

630ae5583186bf0a5d99c97bca68b41401cf6b4b1d22f770fa4f757d23dc240e

$ curl http://127.0.0.1:6000

Hello, Docker!


Linux Containers for GCC

BellSoft provides Alpaquita Linux images with the GCC compiler version 12.2, tools, and libraries for development in C/C++. Two libc options (BellSoft’s musl perf and glibc) are available.

We will use a C++ example to show that our GCC image could be used for building both C++ and C projects.

Our GCC images include the following packages that are not obligatory but could be useful for building:

C++
 
autoconf automake bash binutils bzip2 bzip2-dev curl curl-dev diffutils file findutils fortify-headers g++ gawk gcc gdb git grep hexdump jpeg-dev krb5-dev libevent-dev libffi-dev libjpeg-turbo-dev libpng-dev libtool libxml2-dev libxslt-dev make ncurses-dev openssl-dev patch pkgconf readline-dev sed subversion unzip xz xz-dev yaml-dev zlib-dev


First, let’s write a simple C++ program:

C++
 
$ cat hello.cpp

#include <iostream>

using namespace std;

int main()

{

    cout << "Hello World" << endl;

    return 0;

}


In the Dockerfile, specify an Alpaquita image for building an app, and a base image, which will be used for working with the container further on:

Dockerfile
 
FROM bellsoft/alpaquita-linux-gcc:12.2-stream-musl as builder

WORKDIR /home/myapp

COPY hello.cpp .

RUN g++ hello.cpp -o hello -static

FROM bellsoft/alpaquita-linux-base:stream-musl

WORKDIR /home/myapp

COPY --from=builder /home/myapp/hello .

CMD ["./hello"]


Now, build the Docker container image:

Dockerfile
 
$ docker build -t cppappimage .

Run it with the following command:

$ docker run --rm cppappimage

Hello World 


Conclusion

In this article, we learned how to construct Linux containers with Java, Python, C/C++ applications, and Native Image. We used Alpaquita Stream as a base Linux distribution.

As you can see, containerization with Alpaquita is fast and effortless, and in the end, you get a performant microcontainer that can be used as is or further configured for specific purposes.

Docker (software) Linux (operating system) Python (language) Container Java (programming language)

Published at DZone with permission of Dmitry Chuyko. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How Agile Architecture Spikes Are Used in Shift-Left BDD
  • Building a REST API With AWS Gateway and Python
  • How To Build a Spring Boot GraalVM Image
  • Best Practices for Writing Clean and Maintainable Code

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: