Skip to content

Commit

Permalink
feat(node): add docker as a build target (#14475)
Browse files Browse the repository at this point in the history
  • Loading branch information
ndcunningham authored Jan 20, 2023
1 parent 7857ae0 commit 0e018e6
Show file tree
Hide file tree
Showing 14 changed files with 282 additions and 0 deletions.
8 changes: 8 additions & 0 deletions docs/generated/manifests/menus.json
Original file line number Diff line number Diff line change
Expand Up @@ -5015,6 +5015,14 @@
"children": [],
"isExternal": false,
"disableCollapsible": false
},
{
"id": "setup-docker",
"path": "/packages/node/generators/setup-docker",
"name": "setup-docker",
"children": [],
"isExternal": false,
"disableCollapsible": false
}
],
"isExternal": false,
Expand Down
9 changes: 9 additions & 0 deletions docs/generated/manifests/packages.json
Original file line number Diff line number Diff line change
Expand Up @@ -1554,6 +1554,15 @@
"originalFilePath": "/packages/node/src/generators/library/schema.json",
"path": "/packages/node/generators/library",
"type": "generator"
},
"/packages/node/generators/setup-docker": {
"description": "Set up Docker configuration for a project.",
"file": "generated/packages/node/generators/setup-docker.json",
"hidden": false,
"name": "setup-docker",
"originalFilePath": "/packages/node/src/generators/setup-docker/schema.json",
"path": "/packages/node/generators/setup-docker",
"type": "generator"
}
},
"path": "/packages/node"
Expand Down
9 changes: 9 additions & 0 deletions docs/generated/packages-metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -1531,6 +1531,15 @@
"originalFilePath": "/packages/node/src/generators/library/schema.json",
"path": "node/generators/library",
"type": "generator"
},
{
"description": "Set up Docker configuration for a project.",
"file": "generated/packages/node/generators/setup-docker.json",
"hidden": false,
"name": "setup-docker",
"originalFilePath": "/packages/node/src/generators/setup-docker/schema.json",
"path": "node/generators/setup-docker",
"type": "generator"
}
],
"githubRoot": "https://github.com/nrwl/nx/blob/master",
Expand Down
4 changes: 4 additions & 0 deletions docs/generated/packages/node/generators/application.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@
"enum": ["jest", "none"],
"description": "Test runner to use for end to end (e2e) tests",
"default": "jest"
},
"docker": {
"type": "boolean",
"description": "Add a docker build target"
}
},
"required": [],
Expand Down
36 changes: 36 additions & 0 deletions docs/generated/packages/node/generators/setup-docker.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "setup-docker",
"factory": "./src/generators/setup-docker/setup-docker",
"schema": {
"$schema": "http://json-schema.org/schema",
"cli": "nx",
"$id": "SchematicsNxSetupDocker",
"title": "Nx Node Docker Options Schema",
"description": "Nx Node Docker Options Schema.",
"type": "object",
"properties": {
"projectName": {
"description": "The name of the project",
"$default": { "$source": "argv", "index": 0 },
"type": "string"
},
"targetName": {
"description": "The name of the target to create",
"type": "string",
"default": "docker-build"
},
"buildTargetName": {
"description": "The name of the build target",
"type": "string",
"default": "build"
}
},
"presets": []
},
"description": "Set up Docker configuration for a project.",
"hidden": false,
"implementation": "/packages/node/src/generators/setup-docker/setup-docker.ts",
"aliases": [],
"path": "/packages/node/src/generators/setup-docker/schema.json",
"type": "generator"
}
11 changes: 11 additions & 0 deletions packages/node/generators.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@
"aliases": ["lib"],
"x-type": "library",
"description": "Create a node library."
},
"setup-docker": {
"factory": "./src/generators/setup-docker/setup-docker",
"schema": "./src/generators/setup-docker/schema.json",
"description": "Set up Docker configuration for a project.",
"hidden": false
}
},
"schematics": {
Expand All @@ -46,6 +52,11 @@
"aliases": ["lib"],
"x-type": "library",
"description": "Create a node library."
},
"setup-docker": {
"factory": "./src/generators/setup-docker/setup-docker#setupDockerGenerator",
"schema": "./src/generators/setup-docker/schema.json",
"description": "Set up Docker configuration for a project."
}
}
}
10 changes: 10 additions & 0 deletions packages/node/src/generators/application/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {

import * as shared from '@nrwl/workspace/src/utils/create-ts-config';
import { e2eProjectGenerator } from '../e2e-project/e2e-project';
import { setupDockerGenerator } from '../setup-docker/setup-docker';

export interface NormalizedSchema extends Schema {
appProjectRoot: string;
Expand Down Expand Up @@ -374,6 +375,15 @@ export async function applicationGenerator(tree: Tree, schema: Schema) {
addProxy(tree, options);
}

if (options.docker) {
const dockerTask = await setupDockerGenerator(tree, {
...options,
projectName: options.name,
});

tasks.push(dockerTask);
}

if (!options.skipFormat) {
await formatFiles(tree);
}
Expand Down
1 change: 1 addition & 0 deletions packages/node/src/generators/application/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface Schema {
framework?: NodeJsFrameWorks;
port?: number;
rootProject?: boolean;
docker?: boolean;
}

export type NodeJsFrameWorks =
Expand Down
4 changes: 4 additions & 0 deletions packages/node/src/generators/application/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@
"enum": ["jest", "none"],
"description": "Test runner to use for end to end (e2e) tests",
"default": "jest"
},
"docker": {
"type": "boolean",
"description": "Add a docker build target"
}
},
"required": []
Expand Down
11 changes: 11 additions & 0 deletions packages/node/src/generators/setup-docker/files/Dockerfile__tmpl__
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM docker.io/node:lts-alpine

WORKDIR /app

RUN addgroup --system <%= projectName %> && \
adduser --system -G <%= projectName %> <%= projectName %>

COPY <%= buildLocation %> dist
RUN chown -R <%= projectName %>:<%= projectName %> .

CMD [ "node", "dist" ]
6 changes: 6 additions & 0 deletions packages/node/src/generators/setup-docker/schema.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface SetUpDockerOptions {
projectName?: string;
targetName?: string;
buildTarget?: string;
skipFormat?: boolean;
}
25 changes: 25 additions & 0 deletions packages/node/src/generators/setup-docker/schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"$schema": "http://json-schema.org/schema",
"cli": "nx",
"$id": "SchematicsNxSetupDocker",
"title": "Nx Node Docker Options Schema",
"description": "Nx Node Docker Options Schema.",
"type": "object",
"properties": {
"projectName": {
"description": "The name of the project",
"$default": { "$source": "argv", "index": 0 },
"type": "string"
},
"targetName": {
"description": "The name of the target to create",
"type": "string",
"default": "docker-build"
},
"buildTargetName": {
"description": "The name of the build target",
"type": "string",
"default": "build"
}
}
}
60 changes: 60 additions & 0 deletions packages/node/src/generators/setup-docker/setup-docker.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { readProjectConfiguration, Tree } from '@nrwl/devkit';
import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing';
import { applicationGenerator } from '../application/application';
describe('setupDockerGenerator', () => {
let tree: Tree;
beforeEach(async () => {
tree = createTreeWithEmptyWorkspace();
});

describe('integrated', () => {
it('should create docker assets when --docker is passed', async () => {
await applicationGenerator(tree, {
name: 'api',
framework: 'express',
e2eTestRunner: 'none',
docker: true,
});

const project = readProjectConfiguration(tree, 'api');

expect(tree.exists('api/Dockerfile')).toBeTruthy();
expect(project.targets).toEqual(
expect.objectContaining({
'docker-build': {
dependsOn: ['build'],
executor: 'nx:run-commands',
options: {
commands: ['docker build -f api/Dockerfile .'],
},
},
})
);
});
});

describe('standalone', () => {
it('should create docker assets when --docker is passed', async () => {
await applicationGenerator(tree, {
name: 'api',
framework: 'fastify',
rootProject: true,
docker: true,
});

const project = readProjectConfiguration(tree, 'api');
expect(tree.exists('Dockerfile')).toBeTruthy();
expect(project.targets).toEqual(
expect.objectContaining({
'docker-build': {
dependsOn: ['build'],
executor: 'nx:run-commands',
options: {
commands: ['docker build -f Dockerfile .'],
},
},
})
);
});
});
});
88 changes: 88 additions & 0 deletions packages/node/src/generators/setup-docker/setup-docker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import {
addDependenciesToPackageJson,
convertNxGenerator,
formatFiles,
generateFiles,
GeneratorCallback,
joinPathFragments,
logger,
readNxJson,
readProjectConfiguration,
Tree,
updateProjectConfiguration,
} from '@nrwl/devkit';
import { runTasksInSerial } from '@nrwl/workspace/src/utilities/run-tasks-in-serial';
import { SetUpDockerOptions } from './schema';

function normalizeOptions(
tree: Tree,
setupOptions: SetUpDockerOptions
): SetUpDockerOptions {
return {
...setupOptions,
projectName: setupOptions.projectName ?? readNxJson(tree).defaultProject,
targetName: setupOptions.targetName ?? 'docker-build',
buildTarget: setupOptions.buildTarget ?? 'build',
};
}

function addDocker(tree: Tree, options: SetUpDockerOptions) {
const project = readProjectConfiguration(tree, options.projectName);
if (!project || !options.targetName) {
return;
}

if (tree.exists(joinPathFragments(project.root, 'DockerFile'))) {
logger.info(
`Skipping setup since a Dockerfile already exists inside ${project.root}`
);
} else {
const outputPath =
project.targets[`${options.buildTarget}`]?.options.outputPath;
generateFiles(tree, joinPathFragments(__dirname, './files'), project.root, {
tmpl: '',
app: project.sourceRoot,
buildLocation: outputPath,
projectName: options.projectName,
});
}
}

export function updateProjectConfig(tree: Tree, options: SetUpDockerOptions) {
let projectConfig = readProjectConfiguration(tree, options.projectName);

projectConfig.targets[`${options.targetName}`] = {
dependsOn: [`${options.buildTarget}`],
executor: 'nx:run-commands',
options: {
commands: [
`docker build -f ${joinPathFragments(
projectConfig.root,
'Dockerfile'
)} .`,
],
},
};

updateProjectConfiguration(tree, options.projectName, projectConfig);
}

export async function setupDockerGenerator(
tree: Tree,
setupOptions: SetUpDockerOptions
) {
const tasks: GeneratorCallback[] = [];
const options = normalizeOptions(tree, setupOptions);
// Should check if the node project exists
addDocker(tree, options);
updateProjectConfig(tree, options);

if (!options.skipFormat) {
await formatFiles(tree);
}

return runTasksInSerial(...tasks);
}

export default setupDockerGenerator;
export const setupDockerSchematic = convertNxGenerator(setupDockerGenerator);

1 comment on commit 0e018e6

@vercel
Copy link

@vercel vercel bot commented on 0e018e6 Jan 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

nx-dev – ./

nx-dev-git-master-nrwl.vercel.app
nx-dev-nrwl.vercel.app
nx.dev
nx-five.vercel.app

Please sign in to comment.