How can I deploy a dockerized Node app to a DigitalOcean server using Bitbucket Pipelines?

Viewed 521

I've got a NodeJS project in a Bitbucket repo, and I am struggling to understand how to use Bitbucket Pipelines to get it from there onto my DigitalOcean server, where it can be served on the web.

So far I've got this

image: node:10.15.3

pipelines:
  default:
    - parallel:
        - step:
            name: Build
            caches:
              - node
            script:
              - npm run build

So now the app was built and should be saved as a single file server.js in a theoretical /dist directory.

How now do I dockerize this file and then upload it to my DigitalOcean? I can't find any examples for something like this.

I did find a Docker template in the Bitbucket Pipelines editor, but it only somewhat describes creating a Docker image, and not at all how to actually deploy it to a DigitalOcean server (or anywhere)

  - step:
      name: Build and Test
      script:
        - IMAGE_NAME=$BITBUCKET_REPO_SLUG
        - docker build . --file Dockerfile --tag ${IMAGE_NAME}
        - docker save ${IMAGE_NAME} --output "${IMAGE_NAME}.tar"
      services:
        - docker
      caches:
        - docker
      artifacts:
        - "*.tar"
  - step:
      name: Deploy to Production
      deployment: Production
      script:
        - echo ${DOCKERHUB_PASSWORD} | docker login --username "$DOCKERHUB_USERNAME" --password-stdin
        - IMAGE_NAME=$BITBUCKET_REPO_SLUG
        - docker load --input "${IMAGE_NAME}.tar"
        - VERSION="prod-0.1.${BITBUCKET_BUILD_NUMBER}"
        - IMAGE=${DOCKERHUB_NAMESPACE}/${IMAGE_NAME}
        - docker tag "${IMAGE_NAME}" "${IMAGE}:${VERSION}"
        - docker push "${IMAGE}:${VERSION}"
      services:
        - docker
1 Answers

You would have to SSH into your DigitalOcean VPS and then do some steps there:

  • Pull the current code
  • Build the docker file
  • Deploy the docker file

An example could look like this:

Create some script like "deployment.sh" in your repository root:

cd <path_to_local_repo>
git pull origin master
docker container stop <container_name>
docker container rm <container_name>
docker image build -t <image_name> .
docker container run -itd --name <container_name> <image_name>

and then add the following into your pipeline:

# ...
    - step:
        deployment: staging
        script:
          - cat ./deployment.sh | ssh <ssh_user>@<ssh_host>

You have to add your ssh key for your repository on your server, though. Check out the following link, on how to do this: https://confluence.atlassian.com/display/BITTEMP/Use+SSH+keys+in+Bitbucket+Pipelines

Here is a similar question, but using PHP: Using BitBucket Pipelines to Deploy onto VPS via SSH Access

Related