Continuously Deploy Your Frontend using Gitlab and Scotty.JS
โจiMichaelโจ
Posted on August 5, 2018
My lovefest for Gitlab continues! Heres a quick post showing you how to continuously deploy your React/Vue/Angular Single Page Applications to S3 and Cloudfront, using just Docker, Gitlab and great tool called Scotty.JS.
First save AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
to your Gitlab environment variables (I recommend a special IAM role for this). Then save the files below to your repository and update the placeholder text to what makes sense for your project.
The Dockerfile below performs a multi-stage build that builds the frontend code (Create-React-App) then copies all of it to a directory that Scotty can access.
#Dockerfile
FROM node:8.11.3-slim as node_builder
MAINTAINER @iMichael
WORKDIR /app
COPY /src /app/src
RUN cd /app/src && \
npm install && \
npm run build
FROM node:8.11.3-slim as deployer
RUN groupadd -r react && useradd -r -g react react
RUN npm install scottyjs --global
COPY --from=node_builder /app/src/build /tmp/build
USER react
ENTRYPOINT ["scotty"]
And below is the Gitlab config that ties it all together. Update this with any special logic your team adheres to (like only deploying if all tests pass on the master branch).
#.gitlab-ci.yml
image: docker:latest
services:
- docker:dind
stages:
- build
- push
- deploy
variables:
REACT_TAG_NAME: registry.gitlab.com/<user>/<project>/<container-name>:$CI_COMMIT_REF_NAME
S3_BUCKET: xxxx
before_script:
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN registry.gitlab.com
build:react:
artifacts:
paths:
- docker-images
stage: build
script:
- mkdir docker-images
- docker build --pull -t $REACT_TAG_NAME -f path/to/your/Dockerfile .
- docker save $REACT_TAG_NAME > docker-images/react.tar
push:react:
stage: push
script:
- docker load -i docker-images/react.tar
- docker push $REACT_TAG_NAME
only:
- master
deploy:react:
stage: deploy
script:
- docker run \
--rm \
-e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
-e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
$REACT_TAG_NAME \
--source /tmp/build/ \
--region us-east-1 \
--bucket $S3_BUCKET \
--spa
Now every time you push to master on Gitlab (and all tests pass). your code will be deployed to AWS with a Cloudfront URL that you can CNAME to your own domain.
Big thanks to Scotty.js which does all the heavy lifting!
Posted on August 5, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.