Docker Container Actions

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 10 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Docker Container Actions: A Comprehensive Guide

Introduction: Why Docker Container Actions Matter

In the ecosystem of modern software development, automation is the backbone of efficiency. When we talk about CI/CD pipelines, we often rely on pre-built actions to perform routine tasks like checking out code, setting up environments, or deploying artifacts. However, as projects grow in complexity, you will inevitably reach a point where existing community actions do not meet your specific requirements. This is where custom actions come into play. Among the different types of actions available, Docker Container Actions stand out as the most powerful and flexible option.

A Docker Container Action allows you to package your code, its dependencies, and the specific operating system environment into a single container image. Unlike JavaScript actions, which run directly on the runner’s host environment, Docker actions run in an isolated container. This isolation is crucial because it ensures that your action behaves identically regardless of the underlying runner configuration. Whether you are using a GitHub-hosted runner or a self-hosted runner, the container ensures that the environment is exactly as you defined it in your Dockerfile.

Understanding how to build, maintain, and troubleshoot these actions is a critical skill for any DevOps engineer or developer. By mastering Docker Container Actions, you gain the ability to use any programming language, include complex system-level dependencies, and ensure that your automation logic is portable and predictable. This lesson will guide you through the entire lifecycle of a Docker Container Action, from the initial setup to debugging complex deployment issues.


Not read yet

Anatomy of a Docker Container Action

To create a Docker Container Action, you need to understand the three fundamental components that must exist in your repository. Without these files, the platform cannot recognize your code as an executable action.

1. The Action Metadata File (action.yml)

The action.yml file is the manifest for your action. It tells the CI/CD platform how to execute your container, what inputs it accepts, and what outputs it provides. Unlike other action types, the runs section in a Docker action is specific: it points to the Dockerfile that contains the build instructions.

2. The Dockerfile

The Dockerfile is the blueprint for your environment. Because your action runs inside a container, you are responsible for installing the runtime (e.g., Python, Go, Rust), any system libraries (like libssl or git), and copying your source code into the image.

3. The Entrypoint Script

While you can set a CMD in your Dockerfile, it is standard practice to use an entrypoint script (usually a shell script). This script acts as the bridge between the CI/CD platform's inputs and your actual logic. It handles the parsing of environment variables and executes the main application code.

Callout: Docker Actions vs. JavaScript Actions It is important to distinguish between the two primary ways to write actions. JavaScript actions run directly on the runner's Node.js environment. They are fast but limited by the runner's installed software. Docker Container Actions run in a container, meaning you have full control over the OS and dependencies, but they incur a performance penalty because the runner must pull the image and start the container before the logic executes.


Not read yet

Step-by-Step: Creating Your First Container Action

Let’s walk through the process of creating a simple action that prints a greeting. While this example is basic, it demonstrates the structural requirements necessary for more complex automation.

Step 1: Initialize the Repository

Create a new directory for your action. Inside this directory, create the mandatory action.yml file.

# action.yml
name: 'Hello World Docker Action'
description: 'A simple action that greets the user'
inputs:
  who-to-greet:
    description: 'The name of the person to greet'
    required: true
    default: 'World'
runs:
  using: 'docker'
  image: 'Dockerfile'
  args:
    - ${{ inputs.who-to-greet }}

Step 2: Write the Dockerfile

Next, create the Dockerfile. We will use a lightweight Alpine Linux image to keep our action fast.

# Dockerfile
FROM alpine:3.18

# Copy the entrypoint script into the container
COPY entrypoint.sh /entrypoint.sh

# Make the script executable
RUN chmod +x /entrypoint.sh

# Set the entrypoint
ENTRYPOINT ["/entrypoint.sh"]

Step 3: Create the Entrypoint Script

Create the entrypoint.sh file. This script will receive the input from the args defined in action.yml as a positional argument.

#!/bin/sh -l

# The -l flag ensures the shell is a login shell
echo "Hello $1"

Step 4: Testing Locally

Before pushing to your remote repository, you can test your action by building and running the container manually.

  1. Build the image: docker build -t hello-action .
  2. Run the image: docker run --rm hello-action "Colleague"

If the output says "Hello Colleague", your action is functionally sound.


Not read yet

Deep Dive: Handling Inputs and Outputs

In real-world scenarios, your actions will need to interact with the CI/CD environment dynamically. Inputs allow users to customize the action, and outputs allow the action to pass data to subsequent steps in the pipeline.

Managing Inputs

Inputs are passed to your container as environment variables or as arguments. When you define args in your action.yml, the platform maps those inputs to the container’s command-line arguments. However, if you have many inputs, using environment variables is often cleaner.

The platform automatically maps inputs to environment variables using the prefix INPUT_. For example, an input named github-token becomes INPUT_GITHUB-TOKEN.

Providing Outputs

To provide an output to the workflow, you must write to a specific file defined by the environment variable GITHUB_OUTPUT. This is a unique requirement of modern CI/CD runners.

#!/bin/sh
# Inside entrypoint.sh

# Perform some logic
RESULT="Processed data"

# Write to the output file
echo "processed-result=$RESULT" >> $GITHUB_OUTPUT

Note: Always use the >> append operator when writing to $GITHUB_OUTPUT. If you use >, you will overwrite any previous outputs set by other steps or previous commands, leading to data loss that is notoriously difficult to debug.


Not read yet

Best Practices for Docker Container Actions

Building a container action is easy, but building one that is performant, secure, and maintainable requires adherence to specific industry standards.

1. Optimize Image Size

Since the runner must pull your image every time the action runs, a large image will significantly slow down your pipeline. Use multi-stage builds to separate your build environment from your runtime environment.

# Multi-stage build example
FROM golang:1.21 AS builder
WORKDIR /app
COPY . .
RUN go build -o my-app

FROM alpine:3.18
COPY --from=builder /app/my-app /usr/local/bin/my-app
ENTRYPOINT ["my-app"]

2. Use Specific Tags

Never use the latest tag in your FROM statement. If the base image updates, your action might break unexpectedly. Pin your base image to a specific digest or version (e.g., alpine:3.18.4).

3. Keep Logic Out of the Dockerfile

The Dockerfile should be used only for environment configuration. All business logic should reside in scripts or compiled binaries. This makes your code easier to unit test outside of the container context.

4. Provide Meaningful Logs

Since container actions run in a black box, your logging is the only way to understand what happened if a job fails. Use informative echo statements or log to standard error (>&2) for critical failures.


Not read yet

Troubleshooting Common Pitfalls

Even experienced engineers encounter issues when containerizing actions. Below are the most frequent problems and how to resolve them.

Permission Denied Errors

A common issue occurs when the entrypoint.sh file does not have execution permissions. Because the container runs in a Linux environment, the file must be executable. Always include RUN chmod +x entrypoint.sh in your Dockerfile.

Missing Dependencies

If your script relies on curl, git, or python, ensure they are installed in the Dockerfile. Do not assume the runner has these tools pre-installed inside your container.

Environment Variable Conflicts

The platform injects many environment variables into the container. Be careful not to name your own internal environment variables with prefixes that might conflict with system-reserved variables. Avoid using GITHUB_ as a prefix for your custom variables.

The "Silent Failure"

If your container exits with a non-zero exit code, the workflow will fail, but the logs might be sparse. To debug this, you can add a DEBUG environment variable to your action that triggers verbose logging within your script.

Callout: Debugging with SSH When a container action fails consistently and the logs aren't enough, consider using an action that allows you to SSH into the runner. While you cannot SSH into the container directly, you can run a docker run command on the runner itself using the same image and arguments to reproduce the environment exactly.


Not read yet

Comparison Table: Action Types

When deciding whether to use a Docker Container Action or another type, refer to the following comparison to ensure you are choosing the right tool for the job.

Feature Docker Container Action JavaScript Action Composite Action
Performance Slower (pull/start time) Fast Very Fast
Environment Isolated/Custom Shared/Node.js Shared/Host
Dependencies Any (C++, Go, Python, etc.) Node.js only Shell/Platform tools
Complexity High Medium Low
Portability Excellent Good Moderate

Advanced Implementation: Handling Secrets and Tokens

Security is paramount when writing actions. You will often need to interact with APIs that require authentication. Never hardcode tokens in your Dockerfile or your script.

Using Inputs for Secrets

When a user provides a secret, it is passed into your action as an input. You should define these inputs as required: true in your action.yml.

inputs:
  api-token:
    description: 'The API token for the service'
    required: true

Masking Secrets

If you want to ensure your action does not accidentally print the secret to the logs, you can use the logging commands provided by the runner.

# Masking a secret in the logs
echo "::add-mask::$API_TOKEN"

Once a string is masked, any instance of that string appearing in the workflow logs will be replaced with asterisks (***). This is an essential security practice to prevent accidental credential leakage in public logs.


Not read yet

Managing Versions and Distribution

Once your action is ready, you need to distribute it. In the world of CI/CD actions, versioning is done via Git tags.

  1. Tagging: Always tag your releases (e.g., v1.0.0, v1.1.2).
  2. Branching: You can point your workflow to v1 (the branch) or v1.0.0 (the specific tag). Using a branch tag like v1 is recommended as it allows you to push minor bug fixes without requiring your users to update their workflow files.
  3. Documentation: Include a README.md in your repository. Explain what the action does, provide a sample workflow usage snippet, and list all required inputs and outputs.

Summary of Best Practices

To ensure your Docker Container Actions remain robust and useful for your team, follow these rules:

  • Keep it focused: An action should do one thing well. If your action is becoming too large, split it into two separate actions.
  • Handle errors gracefully: Always exit with a non-zero status code (exit 1) if an error occurs. This ensures the workflow stops and the user is alerted.
  • Document your inputs: Use the description field in action.yml effectively. Users should know exactly what format to provide.
  • Automate your testing: Use a separate workflow to test your action. When you make changes to the Dockerfile, run a test workflow that uses the local version of the action to verify it still works.
  • Minimize layers: In your Dockerfile, combine RUN commands using && to reduce the number of layers in your image. This keeps the image size small and the build time fast.

Not read yet

Frequently Asked Questions (FAQ)

Q: Can I use a private Docker registry?

A: Yes. You can use any image from a registry, provided that the runner has the necessary authentication to pull that image. You would typically configure the registry credentials in your workflow before the action runs.

Q: Why is my action so slow to start?

A: The primary cause is image size. If your image is several gigabytes, the runner spends more time pulling the image than executing your code. Use smaller base images like Alpine or Distroless to reduce the footprint.

Q: Can I run multiple containers in one action?

A: No. A Docker Container Action is designed to run a single container. If you need multiple services (e.g., an app and a database), use the services keyword in your workflow file instead of trying to bake the database into the action itself.

Q: How do I handle large files?

A: Do not pass large files as inputs. Instead, pass a file path or a workspace location. Use the runner's workspace volume to share data between steps.


Not read yet

Key Takeaways

  1. Isolation is the primary benefit: Docker Container Actions provide a consistent environment, eliminating the "it works on my machine" problem by bundling dependencies and OS-level configurations.
  2. Structural Integrity: Every Docker action requires three specific files: action.yml (manifest), Dockerfile (environment definition), and an entrypoint script (execution logic).
  3. Output Management: Always use the $GITHUB_OUTPUT file to communicate data back to the workflow. Remember to use the append (>>) operator to prevent overwriting existing outputs.
  4. Performance Matters: Optimize your images using multi-stage builds and lightweight base images. A lean image results in faster, more responsive CI/CD pipelines.
  5. Security First: Use secret masking (::add-mask::) to prevent sensitive data from appearing in logs, and never hardcode credentials into your container images.
  6. Version Control: Utilize Git tags to manage versions. This allows users of your action to pin to a specific version, ensuring stability as you iterate on your code.
  7. Test Locally: Always verify your container logic locally using Docker commands before pushing to your repository. This saves time and prevents unnecessary pipeline failures.

By following these principles, you will be able to create, maintain, and scale custom actions that significantly enhance your team's automation capabilities. Docker Container Actions provide the ultimate level of control, making them an indispensable tool for advanced pipeline engineering.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.