How to setup Scala and SBT on Docker?

How to setup Scala and SBT on Docker?

  • Post Author:

In this article we are going to show you how to setup Scala in docker container as well as how to setup sbt and docker compose.

What is sbt?

SBT is a build tool for Scala and Java projects for compiling Scala code and integrating with many Scala test frameworks. Continuous compilation, testing and deployment.

What is docker compose?

Docker compose is a tool for defining and running multi-container Docker applications.

Prerequisite Installation

Assume that we already installed Docker and Docker Compose.

Steps for Implementing Docker Compose

There are 3 steps for implementing docker compose:

  1. Create a Dockerfile for running commands
  2. Define services to run applications in docker-compose.yml file
  3. Start and run scala with the help of docker-compose.yml file

1. Create a Dockerfile for running commands

Create a file named Dockerfile in the root of project with following content:

# Install Java and set the JAVA_HOME variable
FROM openjdk:8
ENV JAVA_HOME /usr/lib/jvm/java-1.8-openjdk
ENV PATH $PATH:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin

ENV SBT_VERSION 1.3.3

# Install curl and vim
RUN \
  apt-get update && \
  apt-get -y install curl && \
  apt-get -y install vim

# Install both scala and sbt
RUN \
  curl -L -o sbt-$SBT_VERSION.deb https://repo.scala-sbt.org/scalasbt/debian/sbt-$SBT_VERSION.deb && \
  dpkg -i sbt-$SBT_VERSION.deb && \
  rm sbt-$SBT_VERSION.deb && \
  apt-get update && \
  apt-get -y install sbt

WORKDIR /root/my-app
COPY . /root/my-app

Create Hello.scala in nested directories src/main/scala/example using your favorite editor as follows:

package example

object Hello extends App {
  println("Hello")
}

2. Define services to run applications in docker-compose.yml file

Create a file named docker-compose.yml in the root of project with following content:

version: '3.1'

services:
  app:
    build:
      context: ./
    ports:
      - "9000:9000"
    volumes:
      - "./:/root/build"

  # .sbt, .ivy2 and .m2 cache directories
  sbt:
    build:
      context: ./
    image: sbt
    volumes:
      - ~/.sbt:/root/.sbt
      - ~/.ivy2:/root/.ivy2
      - ~/.m2:/root/.m2

3. Start and run scala with the help of docker-compose.yml file

Run command below to up docker container:

$ docker-compose up

To use sbt commands we need to bash into container using docker-compose command below:

$ docker-compose run --service-ports sbt /bin/bash

To start sb shell:

$ sbt

To compile an app:

$ compile

To run an app:

$ run

We enjoy the docker approach towards developing Scala applications since it keeps the environment consistent across machines.

we are hiring

優秀な技術者と一緒に、好きな場所で働きませんか

株式会社もばらぶでは、優秀で意欲に溢れる方を常に求めています。働く場所は自由、働く時間も柔軟に選択可能です。

現在、以下の職種を募集中です。ご興味のある方は、リンク先をご参照下さい。

コメントを残す