### Complete Docker Build Example with Task Handling Source: https://context7.com/tritondatacenter/sdc-docker-build/llms.txt Demonstrates a full Docker build process using the sdc-docker-build library. It includes setting up the builder, streaming output, handling various build tasks (like file extraction and command execution), and processing the build completion event. Dependencies include 'sdc-docker-build', 'bunyan', 'child_process', and 'mkdirp'. ```javascript const dockerbuild = require('sdc-docker-build'); const bunyan = require('bunyan'); const child_process = require('child_process'); const mkdirp = require('mkdirp'); const log = bunyan.createLogger({ name: 'docker-build', level: 'info' }); const zoneUuid = 'abc-123-def'; const builder = new dockerbuild.Builder({ log: log, uuid: zoneUuid, commandType: 'build', contextFilepath: '/var/tmp/myapp-context.tar', workDir: '/var/tmp/dockerbuild', containerRootDir: '/zones/' + zoneUuid + '/root', buildargs: JSON.stringify({ NODE_ENV: 'production' }), labels: JSON.stringify({ maintainer: 'dev@example.com' }) }); // Stream build output to console builder.on('message', function(event) { process.stdout.write(event.message); }); // Handle build tasks builder.on('task', function(task) { switch (task.type) { case 'extract_tarfile': mkdirp(task.extractDir, function(err) { if (err) return task.callback(err); const cmd = 'tar -xf ' + task.tarfile + ' -C ' + task.extractDir; child_process.exec(cmd, function(err) { task.callback(err); }); }); break; case 'image_reprovision': // Look up image from registry/local store lookupImage(task.imageName, function(err, img) { task.callback(err, img); }); break; case 'run': // Execute command in container runInZone(zoneUuid, task.cmd, task.env, task.workdir, function(err, exitCode) { task.callback(err, { exitCode: exitCode }); }); break; case 'find_cached_image': // Check image cache checkCache(task.parentDigest, task.cmd, function(err, cached) { task.callback(err, cached); }); break; } }); // Handle build completion builder.on('end', function(err) { if (err) { console.error('Build failed:', err.message); process.exit(1); } console.log('\nBuild completed successfully'); console.log('Image ID:', builder.imageDigest); console.log('Short ID:', builder.getShortId()); console.log('Total layers:', builder.layers.length); // Access final image configuration const config = builder.image.config; console.log('CMD:', config.Cmd); console.log('ENV:', config.Env); console.log('WORKDIR:', config.WorkingDir); }); // Start the build builder.start(); ``` -------------------------------- ### Start Docker Build Process Source: https://context7.com/tritondatacenter/sdc-docker-build/llms.txt Initiates the Docker build process by parsing the Dockerfile and executing instructions sequentially. It includes event listeners for build completion ('end') to handle success or failure and log the build results. ```javascript const dockerbuild = require('sdc-docker-build'); const builder = new dockerbuild.Builder({ log: log, uuid: zoneUuid, commandType: 'build', contextFilepath: '/path/to/context.tar', workDir: '/var/tmp/build', containerRootDir: '/zones/' + zoneUuid + '/root' }); // Listen for build completion builder.on('end', function(err) { if (err) { console.error('Build failed:', err.message); return; } console.log('Successfully built', builder.getShortId()); console.log('Final image layers:', builder.layers); }); // Start the build builder.start(); ``` -------------------------------- ### Shell Variable Parsing with sdc-docker-build Source: https://context7.com/tritondatacenter/sdc-docker-build/llms.txt This snippet showcases the use of the shellparser module to perform variable substitution in strings. It supports common shell syntax like $VAR, ${VAR}, ${VAR:-default}, and ${VAR:+alternate}. The example demonstrates how to substitute variables with their values, provide default values, and use alternate values based on variable presence. ```javascript const shellparser = require('sdc-docker-build/lib/shellparser'); // Environment variables as array of 'KEY=value' strings const env = [ 'HOME=/root', 'PATH=/usr/bin:/bin', 'APP_NAME=myapp', 'DEBUG=' ]; // Simple variable substitution console.log(shellparser.processWord('$HOME/config', env)); // Output: '/root/config' // Brace syntax console.log(shellparser.processWord('${APP_NAME}.log', env)); // Output: 'myapp.log' // Default value when variable is empty/unset console.log(shellparser.processWord('${MISSING:-default}', env)); // Output: 'default' console.log(shellparser.processWord('${DEBUG:-enabled}', env)); // Output: 'enabled' (DEBUG is empty) // Alternate value when variable is set console.log(shellparser.processWord('${APP_NAME:+app is set}', env)); // Output: 'app is set' // Quoted strings console.log(shellparser.processWord('"Hello $APP_NAME"', env)); // Output: 'Hello myapp' // Single quotes preserve literal content console.log(shellparser.processWord("'$APP_NAME'", env)); // Output: '$APP_NAME' ``` -------------------------------- ### Initialize Docker Builder Instance Source: https://context7.com/tritondatacenter/sdc-docker-build/llms.txt Creates a new Builder instance for processing Docker build contexts and generating images. It requires configuration options such as logging, command type, context file path, and working directory. ```javascript const dockerbuild = require('sdc-docker-build'); const bunyan = require('bunyan'); const log = bunyan.createLogger({ name: 'docker-build' }); const builder = new dockerbuild.Builder({ log: log, uuid: 'zone-uuid-here', commandType: 'build', // 'build' or 'commit' contextFilepath: '/path/to/context.tar', workDir: '/var/tmp/dockerbuild', containerRootDir: '/zones/abc123/root', dockerfile: 'Dockerfile', // optional, defaults to 'Dockerfile' buildargs: '{"NODE_ENV":"production"}', // optional JSON string labels: '{"version":"1.0"}', // optional JSON string nocache: false, // optional, disable caching suppressSuccessMsg: false // optional, suppress success message }); ``` -------------------------------- ### Calculate File SHA-256 with sdc-docker-build Source: https://context7.com/tritondatacenter/sdc-docker-build/llms.txt This snippet demonstrates calculating the SHA-256 hash of a file using the fileGetSha256 function. It provides both asynchronous and synchronous versions. The asynchronous version takes a callback to handle the result, while the synchronous version returns the hash directly. This is useful for content-based caching or file integrity checks. ```javascript const utils = require('sdc-docker-build/lib/utils'); // Async version utils.fileGetSha256('/path/to/file.txt', function(err, hash) { if (err) { console.error('Hash error:', err); return; } console.log('SHA-256:', hash); // Output: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' }); // Sync version const hash = utils.fileGetSha256Sync('/path/to/file.txt'); console.log('SHA-256:', hash); ``` -------------------------------- ### Handle External Build Tasks Source: https://context7.com/tritondatacenter/sdc-docker-build/llms.txt Responds to 'task' events emitted by the builder, which signal the need for external operations. Handlers must implement logic for tasks like extracting tarfiles, provisioning images, running commands in containers, and finding cached image layers, calling task.callback upon completion. ```javascript builder.on('task', function(task) { if (task.type === 'extract_tarfile') { // Extract tarfile to the specified directory // task.tarfile: path to the tar archive // task.extractDir: destination directory // task.compression: 'gzip', 'bzip2', 'xz', or null extractTar(task.tarfile, task.extractDir, task.compression, function(err) { task.callback(err); }); } if (task.type === 'image_reprovision') { // Reprovision the container with the specified image // task.imageName: the image digest/name to provision // task.cmdName: the Dockerfile command requesting this lookupAndProvisionImage(task.imageName, function(err, imageData) { task.callback(err, imageData); }); } if (task.type === 'run') { // Execute a command inside the container // task.cmd: array of command arguments // task.workdir: working directory for the command // task.env: array of environment variables // task.user: user to run the command as executeInContainer(task.cmd, task.workdir, task.env, task.user, function(err, result) { task.callback(err, { exitCode: result.exitCode }); }); } if (task.type === 'find_cached_image') { // Look up a cached image layer // task.cmd: the NOP command string // task.parentDigest: parent image digest // task.labels: image labels findCachedLayer(task.parentDigest, task.cmd, function(err, cachedImage) { task.callback(err, cachedImage); // null if not cached }); } }); ``` -------------------------------- ### Handle Build Progress Messages Source: https://context7.com/tritondatacenter/sdc-docker-build/llms.txt Listens for the 'message' event emitted by the builder, which provides notifications about build progress. This includes standard output (stdout) from build steps and any success or error messages. ```javascript builder.on('message', function(event) { // event.type is 'stdout' // event.message contains the build output process.stdout.write(event.message); }); // Example output events during build: // { type: 'stdout', message: 'Step 1/4 : FROM busybox\n' } // { type: 'stdout', message: ' ---> abc123def456\n' } // { type: 'stdout', message: 'Step 2/4 : COPY hello /\n' } // { type: 'stdout', message: ' ---> 789xyz012345\n' } // { type: 'stdout', message: 'Successfully built 789xyz012345\n' } ``` -------------------------------- ### Build Image Commit with sdc-docker-build Source: https://context7.com/tritondatacenter/sdc-docker-build/llms.txt This snippet demonstrates creating a new image from container changes, similar to 'docker commit'. It uses the sdc-docker-build library to define the base image, apply changes (like environment variables and exposed ports), and commit the changes. The 'end' event is used to handle the completion of the commit operation. ```javascript const dockerbuild = require('sdc-docker-build'); const builder = new dockerbuild.Builder({ log: log, uuid: zoneUuid, commandType: 'commit', contextFilepath: '/dev/null', // not used for commit workDir: '/var/tmp/commit', containerRootDir: '/zones/' + zoneUuid + '/root', suppressSuccessMsg: true }); // Base image to commit from const fromImg = { config_digest: 'sha256:abc123...', image: { config: { Cmd: ['sh'], Env: ['PATH=/usr/bin'] }, container_config: { Cmd: ['sh'] }, history: [{ created: '2024-01-01T00:00:00Z', created_by: 'base' }] } }; // Changes to apply (subset of Dockerfile commands) const changes = [ 'ENV NODE_ENV=production', 'EXPOSE 8080', 'CMD ["node", "server.js"]' ]; builder.on('end', function(err) { if (err) { console.error('Commit failed:', err); return; } console.log('Committed image:', builder.imageDigest); }); builder.startCommit(fromImg, changes); ``` -------------------------------- ### Detect Compression Type with sdc-docker-build Source: https://context7.com/tritondatacenter/sdc-docker-build/llms.txt This snippet uses the compressionTypeFromPath function to detect the compression type of a file based on its magic number. It supports common compression formats like gzip, bzip2, and xz. The function takes a file path and a callback to return the detected compression type. ```javascript const magic = require('sdc-docker-build/lib/magic'); magic.compressionTypeFromPath('/path/to/archive.tar.gz', function(err, type) { if (err) { console.error('Detection error:', err); return; } // type is one of: 'gzip', 'bzip2', 'xz', or null (uncompressed) console.log('Compression type:', type); // Output for .tar.gz: 'gzip' // Output for .tar.bz2: 'bzip2' // Output for .tar.xz: 'xz' // Output for .tar: null }); ``` -------------------------------- ### Check for Wildcards in Path with sdc-docker-build Source: https://context7.com/tritondatacenter/sdc-docker-build/llms.txt This snippet demonstrates the use of the containsWildcards utility function to check if a given path string contains glob wildcard characters such as *, ?, and []. It is useful for determining if a path represents a pattern or a specific file or directory. ```javascript const utils = require('sdc-docker-build/lib/utils'); console.log(utils.containsWildcards('file.txt')); // false console.log(utils.containsWildcards('*.txt')); // true console.log(utils.containsWildcards('file?.txt')); // true console.log(utils.containsWildcards('file[0-9].txt')); // true console.log(utils.containsWildcards('file\\*.txt')); // false (escaped) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.