Creating a Distroless Node.js 18 Container Image¶
About This Task¶
With an eLxr Server 12 development host, you can either obtain the source or create your own to build a distroless container image that runs a Node.js application as described in this procedure.
When planning your container image, certain frameworks such as Spring Boot, Quarkus, and Micronaut, prefer a build that produces a single runnable JAR, or an exploded application layout, over copying the artifact into the distroless image. This procedure provides such an example.
Before You Begin¶
You must have a development host with Docker installed.
You must have the Node.js Development Kit installed, with npm (Node.js Package Manager).
Procedure¶
Create a directory for the container project and navigate to it.
$ mkdir -p my-distroless-app && cd my-distroless-app
Create a app.js file.
This is for example purposes. For your own container application, substitute this code with you own.
const http = require('http'); const port = process.env.PORT || 8080; const server = http.createServer((req, res) => { res.end('Hello from Node.js Distroless!'); }); server.listen(port, () => { console.log(`Server running on port ${port}`); });
Create a package.json file.
{ "name": "distroless-example", "version": "1.0.0", "main": "app.js", "dependencies": {} }
This example uses the lightweight bundled com.sun.net.httpserver.HttpServer available in the JDK, which keeps the application dependency-free.
Create a multi-stage Dockerfile and name it nodejs-distroless-example.Dockerfile.
This Dockerfile uses a build stage to install dependencies and a production stage that copies only the necessary files to the distroless container image.
Dockerfile # Build stage FROM node:18-slim AS build WORKDIR /app COPY package*.json ./ RUN npm install --production COPY . . # Production stage (distroless Node.js) FROM elxrlinux/elxr:latest-distroless-nodejs18 WORKDIR /app COPY --from=build /app /app CMD ["app.js"]
Build the Docker image.
$ docker build -t nodejs-distroless-example .
Run the container.
$ docker run -p 8080:8080 nodejs-distroless-example .
Visit http://localhost:8080 to see the application respond.
Hello from Node.js Distroless!
Results¶
Now that you have completed the distroless Node.js container image, consider learning about creating distroless Java images. For details, see Creating a Distroless Java 17 Container Image.