Create Grunt Docker image

I didn't like to install special versions of JavaScript libraries globally on my operating system. The same for npm and Grunt. So I need to create small Docker image that fits my needs for development.

Grunt Dockerfile

Here a small Dockerfile that installs npm and Grunt globally based on a Debian image. The EXPOSE is used for a development server like grunt-contrib-connect for example. Feel free to use an other port as 8080.

FROM debian:9

RUN apt-get update \
    && apt-get install -y \
    curl \
    gnupg \
    && curl -sL https://deb.nodesource.com/setup_6.x | bash - \
    && apt-get install -y nodejs \
    && npm install -g grunt-cli

EXPOSE 8080

Build Grunt Docker image

The image can be build with the following command.

docker build -t grunt .

Grunt Docker image usage

In general there are three different tasks that this Grunt Docker image has. To install npm packages, build a small development server and run Grunt tasks.

Minimal Grunt example

Let us have small look at a minimal Grunt project example with the following directory structure.

.
|-- Gruntfile.js
|-- index.html
`-- package.json

Gruntfile.js

A minimal Gruntfile.js with the connect task that opens a development server at port 8080.

module.exports = function( grunt ) {
    "use strict";
    grunt.initConfig( {
        connect: {
            server: {
                options: {
                    base: "",
                    port: 8080
                }
            }
        },
        watch: {}
    } );
    grunt.loadNpmTasks( "grunt-contrib-connect" );
    grunt.loadNpmTasks( "grunt-contrib-watch" );
    grunt.registerTask( "dev", [ "connect", "watch" ] );
};

index.html

A minimal index.html file to test the development server.

<!DOCTYPE html>
<html>
    <head>
        <title>Minimal Grunt Example</title>
    </head>
    <body>
        <h1>Minimal Grunt Example</h1>
    </body>
</html>

package.json

A package.json file to install our dependencies via npm.

{
  "devDependencies": {
    "grunt": "^1.0.1",
    "grunt-contrib-connect": "^1.0.2",
    "grunt-contrib-watch": "^1.0.0"
  }
}

npm install via Docker Grunt container

The following command in the root of the example project will install the dependencies via npm.

docker run --rm -v "$PWD":/usr/src/project -w /usr/src/project grunt npm install

Run Grunt task in Docker container

The following command will show how to run a Grunt task by executing a development server.

docker run --rm -p8080:8080 -v "$PWD":/usr/src/project -w /usr/src/project grunt grunt dev
Running "connect:server" (connect) task
Started connect web server on http://localhost:8080

Running "watch" task
Waiting...

The development server should be available at http://127.0.0.1:9999/.

Next Previous