Gatsby is a ReactJS based open source framework that helps to build web applications real quick .One of the very interesting features of Gatsby is it’s support for creating Progressing Web Apps (PWA ) .
Read more about the framework and it’s capabilities here . https://www.gatsbyjs.org/
In this tutorial we are going to look at how we can run a gatsby application as a docker container .
Before we begin let’s look at how can we create a simple gatsby application and boot it up . Gatsby’s official site has a very good documentation on all of this — https://www.gatsbyjs.org/tutorial/part-zero/#using-the-gatsby-cli
However to put it simple you can boot up a new gatsby application in 3 commands ( assuming you have node and npm already installed )
npm install -g gatsby-cligatsby new hg-gatsby-site
Change to the new project directory
The new gatsby site will be accessible on http://localhost:8000 .It’s that easy to create a new gatsby application .
However building the production distribution we need to use the following commands
Followed by serving the site by
gatsby serve -H 0.0.0.0 -p 8000
-H 0.0.0.0 -p 8000 is optional and you would have guessed it by now that it indicates the host and port respectively .
Let’s dockerize the Gatsby Application
Gatsby is based on ReactJs and hence runs on the nodejs environment , so our base image must provide a NodeJs environment .
So I am choosing the base image from the official nodeJs image node:latest (https://hub.docker.com/_/node/?tab=tags)
Following this we would have to copy the source code files into the image and as you have seen in the previous section it should follow with gatsby build and/or npm build and then finally serving the site by the gatsby serve command . For the gatsby commands we need the gatsby-cli installed in the environment .
Here’s a docker file that would execute the these steps in the right order .
FROM node:latestWORKDIR /appCOPY . .RUN apt-get update &&\
apt-get install -y ca-certificates build-essential autoconf automake libtool pkg-config nasm python &&\
rm -rf node_modules && mkdir node_modules &&\
npm ci --only=production &&\
npm install --global gatsby-cli && gatsby telemetry --disable &&\
npm run buildEXPOSE 8000CMD ["gatsby", "serve", "-H", "0.0.0.0", "-p" ,"8000" ]
The project would be having node_modules and public folder created by the gatsby build in it’s root . We are building node_modules and public folder ( gatsby distribution files) within our image , so we don’t need to copy them into out docker image
However since we are copying all files from the project root , this may cause the docker build context to be very large in size . To avoid this set up a .dockerignore file with the following content .
We are done with the configuration needed for dockerizing the gatsby application .
Now go ahead and build your docker image run it and verify this .
See you again with another post !