Home

Using Deno with Docker the easy way

Security is one of the central ideas behind Deno. It is not, however, the only context where one might want to containerize their Deno applications using Docker.

In this post, we are going to see a few easy ways you can use Docker and Deno together.

Preparation

All examples are going to make use of the hayd/deno DockerHub image. It is the most popular right now and is in the mix of the conversation for an official Deno image.

Run the following in the terminal to pull the image:

Terminal
$ docker pull hayd/deno

Getting a Deno REPL (Read Print Eval Loop)

Terminal
$ docker run -it --entrypoint=deno hayd/deno

Deno 1.0.5
exit using ctrl+d or close()
> const a = 1
undefined
> a + 1
2
>

Running a JavaScript or TypeScript file

Terminal
$ docker run -v $(pwd)/:/deno-dir hayd/deno run /deno-dir/my-file.ts

Explained:

  • docker run: Runs a command in a new container
  • -v $(pwd)/:/deno-dir: mounts the current folder into the container’s /deno-dir directory
  • hayd/deno: The image to be used
  • run /deno-dir/my-file.ts: The command passed to the deno binary

The content of my-file.ts:

./my-file.ts
interface HelloWorld {
  hellow: 'world';
}

const a: HelloWorld = {
  hellow: 'world'
};

console.log(a);

Running a simple Hello world server

The server file used in both examples:

hello-server.js
import { serve } from 'https://deno.land/std@0.55.0/http/server.ts';
const s = serve({ port: 8080 });
console.log('http://localhost:8080/');
for await (const req of s) {
  req.respond({ body: 'Hello World\n' });
}

Method 1: Running server with the command line:

Terminal
$ docker run -v $(pwd)/:/deno-dir -p 8080:8080 hayd/deno run --allow-net /deno-dir/hello-server.ts

Method 2: Running server with docker-compose.yml:

docker-compose.yml
version: '3.1'

services:
  deno:
    image: 'hayd/alpine-deno:1.0.5' # change to desired version
    ports:
      - '8080:8080' # The port that your application listens to.
    user: 'deno'
    volumes:
      - ./:/deno-dir
    command: run --allow-net /deno-dir/hello-server.ts
Terminal
$ docker-compose up

Accessing http://localhost:8080/ should now yield Hello World.

Resources

Deno docs
Hayd/deno on DockerHub