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:
- Create a Dockerfile for running commands
- Define services to run applications in docker-compose.yml file
- 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.