Skip to content

Commit

Permalink
🎉 Use build bind mounts to avoid extra Docker layers
Browse files Browse the repository at this point in the history
  • Loading branch information
LinusU committed Dec 7, 2023
1 parent 370e0f5 commit d0b4a7b
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions lib/dockerfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,22 +49,24 @@ export function generateDockerfile (options) {
lines.push('WORKDIR /var/task')
}

// Copy stripped package files
// These files have the version stripped, so that docker can cache better.
// Stripping is not needed on the yarn lockfile, as that doesn't include pacakge version.
lines.push(`COPY ${directoryPrefix}scandium-clean-package.json package.json`)
lines.push(`COPY ${directoryPrefix}${yarn ? 'yarn.lock yarn.lock' : 'scandium-clean-package-lock.json package-lock.json'}`)

// Add build argument for SSH key, and prime known_hosts with GitHub public key
if (sshKey) lines.push('ARG SSH_PRIVATE_KEY', 'ARG SSH_PUBLIC_KEY', `RUN mkdir -p $HOME/.ssh && echo "${githubPublicKey}" >> $HOME/.ssh/known_hosts`)

// Mount stripped package files
// These files have the version stripped, so that docker can cache better.
// Stripping is not needed on the yarn lockfile, as that doesn't include pacakge version.
const packageFileMounts = [
`--mount=type=bind,source=${directoryPrefix}scandium-clean-package.json,target=package.json`,
`--mount=type=bind,source=${directoryPrefix}${yarn ? 'yarn.lock' : 'scandium-clean-package-lock.json'},target=${yarn ? 'yarn.lock' : 'package-lock.json'}`
].join(' ')

// Add production dependencies
// This step is run before adding the code, to increase docker cache use.
if (hasProductionDependencies && !skipNodeModules) lines.push(`RUN ${sshKey ? sshPrefix : ''}${yarn ? 'yarn install --production --frozen-lockfile' : 'npm ci --production'}${sshKey ? sshPostfix : ''}`)
if (hasProductionDependencies && !skipNodeModules) lines.push(`RUN ${packageFileMounts} ${sshKey ? sshPrefix : ''}${yarn ? 'yarn install --production --frozen-lockfile' : 'npm ci --production'}${sshKey ? sshPostfix : ''}`)
if (hasProductionDependencies && !skipNodeModules) lines.push('RUN zip -9qyr /output.zip node_modules')

// Install dev-dependencies, if there is a `prepare` or `build` script present
if (hasPrepareScript || hasBuildScript) lines.push(`RUN ${sshKey ? sshPrefix : ''}${yarn ? 'yarn install --frozen-lockfile' : 'npm ci'}${sshKey ? sshPostfix : ''}`)
if (hasPrepareScript || hasBuildScript) lines.push(`RUN ${packageFileMounts} ${sshKey ? sshPrefix : ''}${yarn ? 'yarn install --frozen-lockfile' : 'npm ci'}${sshKey ? sshPostfix : ''}`)

// Add the app files, and remove our special files
if (options.directory) {
Expand Down

0 comments on commit d0b4a7b

Please sign in to comment.