Image manipulation in NodeJS on Docker

Problems and how we solved them when using gm, ImageMagick, Docker, and node for image manipulation.

image source:

We needed some image manipulation capabilities in server side. Since our backend is written in NodeJS, we found a library called gm pretty handy and useful for us.

First download and install standalone application called GraphicsMagick or ImageMagick. For our local machine, it is pretty easy. And when I was testing the library functions, they are very straightforward and good. So, I have decided to include in our code base and spin up the Docker image. The problem started there.

The docker container we are using doesn’t have ImageMagick and need to install it using additional command. We used the following command to install in Docker.

RUN apk add --no-cache gettext librsvg ghostscript imagemagick

If you are lucky, that’s all you need to make gm library’s magic working for you. I was not very lucky. We needed to write a text onto images. So, we need a font in our docker image again. You can test if the font you require is in the docker system by following commands.

// get the docker id or name
$ docker ps
// get the available fonts
$ docker exec -it <docker_id> convert -list font
Path: System Fonts
Font: Helvetica
family: Helvetica
style: Normal
stretch: Normal
weight: 500
glyphs: /usr/share/fonts/helvetica/Helvetica.ttf

If you need only that font, you are lucky. I needed Roboto font. So, needed to copy the font file into docker image.

COPY fonts/Roboto-Medium.tff /usr/share/fonts/ttf-roboto/

As the final touch, we just needed to specify the font in the code as following

  .font("Roboto-Medium", font_size)
  .drawText(x, y, overlay_text)
  .write(output_path, function (err) {
    if(!err) {

Finally, our Dockerfile content is as following:

FROM node:8.9.4-alpine
RUN apk add --no-cache gettext librsvg ghostscript imagemagick
COPY fonts/* /usr/share/fonts/ttf-roboto/
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install

Are you excited about Docker, NodeJS, React Native and new technologies? Do you want to be part of a small but fast growing team to work on interesting project about education in Myanmar? If you are willing to learn and take on challenges, please join us for the journey. We are still hiring developers and contact us!