Run Deno in Docker

2020-05-18

Based on this github issue, it looks like there’s still no official Docker image as of the time of this writing, but it’s in the works. In the meantime, here’s a working Docker image if you’d like to play around with Deno without the hassle of installing it locally.

We’ll create a basic web server as an example. First, create a deps.ts file and add the following dependency

export { serve } from "https://deno.land/std@0.50.0/http/server.ts";

Next, create a basic webserver in main.ts

import { serve } from "./deps.ts";

const PORT = 1993;
const s = serve(`0.0.0.0:${PORT}`);
const body = new TextEncoder().encode("Hello World\n");

console.log(`Server started on port ${PORT}`);
for await (const req of s) {
  req.respond({ body });
}

Now we can create the Docker image based on our deno app

From https://hub.docker.com/r/hayd/deno

FROM hayd/alpine-deno:1.0.0

EXPOSE 1993

WORKDIR /app

# Prefer not to run as root.
USER deno

# Cache the dependencies as a layer (this is re-run only when deps.ts is modified).
# Ideally this will download and compile _all_ external files used in main.ts.
COPY deps.ts /app
RUN deno cache deps.ts

# These steps will be re-run upon each file change in your working directory:
ADD . /app
# Compile the main app so that it doesn't need to be compiled each startup/entry.
RUN deno cache main.ts

# These are passed as deno arguments when run with docker:
CMD ["run", "--allow-net", "main.ts"]

And you can run it with this command

docker build -t app . && docker run -it --init -p 1993:1993 app

Now just open up a new terminal or browser to access the url

$ curl localhost:1993
Hello World
public function sayHello(string $name): string
{
    echo "Hello {$name}";
}