Skip to content

Commit

Permalink
feat(node): improve docker setup for Node server apps (#14647)
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysoo committed Jan 26, 2023
1 parent 6093247 commit 9f1ed50
Show file tree
Hide file tree
Showing 14 changed files with 59 additions and 35 deletions.
2 changes: 1 addition & 1 deletion docs/generated/packages/node/generators/application.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
"framework": {
"description": "Generate the node application using a framework",
"type": "string",
"enum": ["express", "koa", "fastify", "none"],
"enum": ["express", "fastify", "koa", "none"],
"default": "none",
"x-prompt": "Which framework do you want to use?",
"x-priority": "important"
Expand Down
8 changes: 5 additions & 3 deletions docs/generated/packages/node/generators/setup-docker.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
"description": "Nx Node Docker Options Schema.",
"type": "object",
"properties": {
"projectName": {
"project": {
"description": "The name of the project",
"$default": { "$source": "argv", "index": 0 },
"type": "string"
"$default": { "$source": "projectName" },
"type": "string",
"x-prompt": "What project would you like to add a Dockerfile to?",
"x-priority": "important"
},
"targetName": {
"description": "The name of the target to create",
Expand Down
8 changes: 4 additions & 4 deletions packages/create-nx-workspace/bin/create-nx-workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -701,14 +701,14 @@ async function determineFramework(
name: 'express',
message: 'Express [https://expressjs.com/]',
},
{
name: 'koa',
message: 'koa [https://koajs.com/]',
},
{
name: 'fastify',
message: 'fastify [https://www.fastify.io/]',
},
{
name: 'koa',
message: 'koa [https://koajs.com/]',
},
];

if (!parsedArgs.framework) {
Expand Down
12 changes: 9 additions & 3 deletions packages/node/src/generators/application/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ function getWebpackBuildConfig(
options: {
target: 'node',
compiler: 'tsc',
outputPath: joinPathFragments('dist', options.appProjectRoot),
outputPath: joinPathFragments(
'dist',
options.rootProject ? options.name : options.appProjectRoot
),
main: joinPathFragments(
project.sourceRoot,
'main' + (options.js ? '.js' : '.ts')
Expand Down Expand Up @@ -90,7 +93,10 @@ function getEsBuildConfig(
executor: '@nrwl/esbuild:esbuild',
outputs: ['{options.outputPath}'],
options: {
outputPath: joinPathFragments('dist', options.appProjectRoot),
outputPath: joinPathFragments(
'dist',
options.rootProject ? options.name : options.appProjectRoot
),
format: ['cjs'],
main: joinPathFragments(
project.sourceRoot,
Expand Down Expand Up @@ -373,7 +379,7 @@ export async function applicationGenerator(tree: Tree, schema: Schema) {
if (options.docker) {
const dockerTask = await setupDockerGenerator(tree, {
...options,
projectName: options.name,
project: options.name,
});

tasks.push(dockerTask);
Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import express from 'express';

const host = process.env.HOST ?? 'localhost';
const port = process.env.PORT ? Number(process.env.PORT) : <%= port %>;

const app = express();
Expand All @@ -8,6 +9,6 @@ app.get('/', (req, res) => {
res.send({ 'message': 'Hello API'});
});

app.listen(port, () => {
console.log(`[ ready ] http://localhost:${port}`);
app.listen(port, host, () => {
console.log(`[ ready ] http://${host}:${port}`);
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fastify from 'fastify';

const host = process.env.HOST ?? 'localhost';
const port = process.env.PORT ? Number(process.env.PORT) : <%= port %>;

const app = fastify();
Expand All @@ -10,8 +11,8 @@ app.get('/', async (req, res) => {

const start = async() => {
try {
await app.listen({ port });
console.log(`[ ready ] http://localhost:${port}`);
await app.listen({ host, port });
console.log(`[ ready ] http://${host}:${port}`);
} catch (err) {
// Errors are logged here
process.exit(1);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import koa from 'koa';

const host = process.env.HOST ?? 'localhost';
const port = process.env.PORT ? Number(process.env.PORT) : <%= port %>;

const app = new koa();
Expand All @@ -8,6 +9,6 @@ app.use(async ctx =>{
ctx.body = { 'message': 'Hello API'};
});

app.listen(port, () => {
console.log(`[ ready ] http://localhost:${port}`);
app.listen(port, host, () => {
console.log(`[ ready ] http://${host}:${port}`);
});
2 changes: 1 addition & 1 deletion packages/node/src/generators/application/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
"framework": {
"description": "Generate the node application using a framework",
"type": "string",
"enum": ["express", "koa", "fastify", "none"],
"enum": ["express", "fastify", "koa", "none"],
"default": "none",
"x-prompt": "Which framework do you want to use?",
"x-priority": "important"
Expand Down
19 changes: 14 additions & 5 deletions packages/node/src/generators/setup-docker/files/Dockerfile__tmpl__
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
# This file is generated by Nx.
#
# Build the docker image with `npx nx docker-build <%= project %>`.
# Tip: Modify "docker-build" options in project.json to change docker build args.
#
# Run the container with `docker run -p 3000:3000 -t <%= project %>`.
FROM docker.io/node:lts-alpine

ENV HOST=0.0.0.0
ENV PORT=3000

WORKDIR /app

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

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

CMD [ "node", "dist" ]
CMD [ "node", "<%= project %>" ]
2 changes: 1 addition & 1 deletion packages/node/src/generators/setup-docker/schema.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export interface SetUpDockerOptions {
projectName?: string;
project?: string;
targetName?: string;
buildTarget?: string;
skipFormat?: boolean;
Expand Down
10 changes: 7 additions & 3 deletions packages/node/src/generators/setup-docker/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@
"description": "Nx Node Docker Options Schema.",
"type": "object",
"properties": {
"projectName": {
"project": {
"description": "The name of the project",
"$default": { "$source": "argv", "index": 0 },
"type": "string"
"$default": {
"$source": "projectName"
},
"type": "string",
"x-prompt": "What project would you like to add a Dockerfile to?",
"x-priority": "important"
},
"targetName": {
"description": "The name of the target to create",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe('setupDockerGenerator', () => {
dependsOn: ['build'],
executor: 'nx:run-commands',
options: {
commands: ['docker build -f api/Dockerfile .'],
commands: ['docker build -f api/Dockerfile . -t api'],
},
},
})
Expand All @@ -50,7 +50,7 @@ describe('setupDockerGenerator', () => {
dependsOn: ['build'],
executor: 'nx:run-commands',
options: {
commands: ['docker build -f Dockerfile .'],
commands: ['docker build -f Dockerfile . -t api'],
},
},
})
Expand Down
12 changes: 6 additions & 6 deletions packages/node/src/generators/setup-docker/setup-docker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@ function normalizeOptions(
): SetUpDockerOptions {
return {
...setupOptions,
projectName: setupOptions.projectName ?? readNxJson(tree).defaultProject,
project: setupOptions.project ?? readNxJson(tree).defaultProject,
targetName: setupOptions.targetName ?? 'docker-build',
buildTarget: setupOptions.buildTarget ?? 'build',
};
}

function addDocker(tree: Tree, options: SetUpDockerOptions) {
const project = readProjectConfiguration(tree, options.projectName);
const project = readProjectConfiguration(tree, options.project);
if (!project || !options.targetName) {
return;
}
Expand All @@ -43,13 +43,13 @@ function addDocker(tree: Tree, options: SetUpDockerOptions) {
tmpl: '',
app: project.sourceRoot,
buildLocation: outputPath,
projectName: options.projectName,
project: options.project,
});
}
}

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

projectConfig.targets[`${options.targetName}`] = {
dependsOn: [`${options.buildTarget}`],
Expand All @@ -59,12 +59,12 @@ export function updateProjectConfig(tree: Tree, options: SetUpDockerOptions) {
`docker build -f ${joinPathFragments(
projectConfig.root,
'Dockerfile'
)} .`,
)} . -t ${options.project}`,
],
},
};

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

export async function setupDockerGenerator(
Expand Down

1 comment on commit 9f1ed50

@vercel
Copy link

@vercel vercel bot commented on 9f1ed50 Jan 26, 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.