Cloud Computing, DevOps

3 Mins Read

Writing Smarter Dockerfiles for Secure and Stable Deployments

Voiced by Amazon Polly

Overview

Imagine deploying your Dockerized app to production. Everything works well until it doesn’t. The container stops responding, but your orchestration platform still thinks it’s healthy. Logs aren’t clear, and you’re running it as root. Worse, your build context accidentally includes a .env file with secrets. Sound familiar?

While most developers are familiar with the basics of Dockerfiles, like FROM, RUN, and CMD, production-grade images demand much more. This post dives into underused but powerful Dockerfile commands that can drastically improve your container’s performance, security, and maintainability. These “hidden gems” can help prevent production nightmares and streamline CI/CD pipelines.

Pioneers in Cloud Consulting & Migration Services

  • Reduced infrastructural costs
  • Accelerated application deployment
Get Started

Introduction

Creating production-grade Dockerfiles goes far beyond simply writing a working container configuration. It involves:

  • Optimizing image size and build time
  • Enhancing container security
  • Improving reliability in orchestration platforms (e.g., Kubernetes)
While commonly used instructions like FROM, RUN, CMD, and EXPOSE are essential, this post explores less commonly used but powerful Dockerfile commands that can improve your images from optimization and security perspectives.

Why Focus on Less Common Dockerfile Commands?

These lesser-known commands are often skipped in quick prototyping but can significantly impact production readiness by:

  • Reducing attack surface
  • Enhancing maintainability
  • Improving CI/CD integration
  • Reducing image size and build complexity

HEALTHCHECK

What It Does:

Defines a command that Docker runs to check container health.

HEALTHCHECK –interval=30s –timeout=3s –retries=3 \
CMD curl -f http://localhost/health || exit 1

Why It’s Useful:

  • Enables orchestration tools (e.g., Kubernetes, Docker Swarm) to know when your container is unhealthy.
  • Prevents serving traffic to faulty containers.

Why It’s Underused:

Many rely only on container start status, ignoring runtime health.

SHELL

What It Does:

Overrides the default shell used for RUN commands.

SHELL [“/bin/bash”, “-c”]

Why It’s Useful:

  • Explicit shell behavior (e.g., using bash over sh when needed).
  • Enables use of shell-specific features like source, loops, and conditional execution.

Example:

SHELL [“/bin/bash”, “-c”]
RUN for i in {1..5}; do echo $i; done

Optimization Insight:

Use carefully, bash is heavier than sh. Default to sh unless advanced scripting is needed.

STOPSIGNAL

What It Does:

Instructs Docker how to properly stop the container.

STOPSIGNAL SIGTERM

Why It’s Useful:

  • Ensures graceful shutdowns by sending the right signal to your application.
  • Prevents data corruption and ensures cleanup operations are triggered.

Security Angle:

Improper shutdowns may leave temporary files or lock files, creating opportunities for exploits in stateful containers.

ONBUILD

What It Does:

Triggers commands in child images built from this image.

ONBUILD COPY . /app
ONBUILD RUN npm install

 Use Case:

Creating base images for internal teams where downstream consumers shouldn’t forget essential setup.

Caveat:

Avoid in public base images. It can introduce unexpected behaviors.

ARG vs ENV

Common Misuse:

People often use ENV for build-time variables.

Correct Practice:

Use ARG for build-time and ENV for runtime values.

ARG NODE_ENV
ENV NODE_ENV=$NODE_ENV

Security Note:

ENV values persist in the image layers. Avoid storing secrets in ENV.

Optimization Tip:

Use ARG for versions:

ARG VERSION=18
FROM node:${VERSION}-alpine

USER

What It Does:

Switches the user from root to a non-privileged user.

RUN addgroup app && adduser -S -G app app
USER app

Why It’s Essential:

  • Reduces attack surface: Running as root inside containers is a bad practice.
  • Limits what an attacker can do if the container is compromised.

Bonus:

Use USER in multi-stage builds only in the final stage.

COPY --chown

 What It Does:

Copies files while changing ownership.

COPY –chown=app:app . /app

Benefits:

  • Avoids extra RUN chown
  • Reduces image layers.
  • Enhances security by ensuring correct permissions.

Example:

RUN addgroup app && adduser -S -G app app
COPY –chown=app:app . /app
USER app

.dockerignore

What It Does:

Specifies files/folders to exclude from the build context.

node_modules
.git
.env
Dockerfile.dev

Optimization Benefits:

  • Reduces build context size.
  • Faster build time.
  • Smaller image size.

Security Angle:

Avoid leaking credentials, tokens, or secrets into the image by ignoring .env or config.json.

Conclusion

Building a working Dockerfile is easy. Building one for production is a discipline. This blog highlighted underutilized but impactful Dockerfile commands that can elevate your containerization practices:

  • Security Enhancements: Use USER, COPY –chown, and STOPSIGNAL to run leaner and safer containers.
  • Performance Boosts: Reduce build size and speed up pipelines with .dockerignore, ARG, and controlled use of SHELL.
  • Operational Resilience: Prevent outages and undefined states using HEALTHCHECK, STOPSIGNAL, and ONBUILD.

Whether you’re deploying on Kubernetes, ECS, or a VM with Docker, these hidden gems can future-proof your containers against common pitfalls and operational headaches. Integrating these techniques also promotes a DevSecOps culture, bringing security and efficiency right into your container builds.

Containers are not just about packaging software, they’re about delivering resilient and secure applications at scale. It all starts with the Dockerfile.

Drop a query if you have any questions regarding Dockerfile and we will get back to you quickly.

Making IT Networks Enterprise-ready – Cloud Management Services

  • Accelerated cloud migration
  • End-to-end view of the cloud environment
Get Started

About CloudThat

CloudThat is a leading provider of Cloud Training and Consulting services with a global presence in India, the USA, Asia, Europe, and Africa. Specializing in AWS, Microsoft Azure, GCP, VMware, Databricks, and more, the company serves mid-market and enterprise clients, offering comprehensive expertise in Cloud Migration, Data Platforms, DevOps, IoT, AI/ML, and more.

CloudThat is the first Indian Company to win the prestigious Microsoft Partner 2024 Award and is recognized as a top-tier partner with AWS and Microsoft, including the prestigious ‘Think Big’ partner award from AWS and the Microsoft Superstars FY 2023 award in Asia & India. Having trained 850k+ professionals in 600+ cloud certifications and completed 500+ consulting projects globally, CloudThat is an official AWS Advanced Consulting Partner, Microsoft Gold Partner, AWS Training PartnerAWS Migration PartnerAWS Data and Analytics PartnerAWS DevOps Competency PartnerAWS GenAI Competency PartnerAmazon QuickSight Service Delivery PartnerAmazon EKS Service Delivery Partner AWS Microsoft Workload PartnersAmazon EC2 Service Delivery PartnerAmazon ECS Service Delivery PartnerAWS Glue Service Delivery PartnerAmazon Redshift Service Delivery PartnerAWS Control Tower Service Delivery PartnerAWS WAF Service Delivery PartnerAmazon CloudFront Service Delivery PartnerAmazon OpenSearch Service Delivery PartnerAWS DMS Service Delivery PartnerAWS Systems Manager Service Delivery PartnerAmazon RDS Service Delivery PartnerAWS CloudFormation Service Delivery PartnerAWS ConfigAmazon EMR and many more.

FAQs

1. Can I use HEALTHCHECK with Kubernetes readiness/liveness probes?

ANS: – Yes, but Kubernetes doesn’t use Docker’s HEALTHCHECK. You must define readinessProbe and livenessProbe in the pod spec separately.

2. Is it okay to run containers as root in development?

ANS: – It’s acceptable for local experiments but always switch to non-root users before moving to production.

WRITTEN BY Akshay Ramnani

Share

Comments

    Click to Comment

Get The Most Out Of Us

Our support doesn't end here. We have monthly newsletters, study guides, practice questions, and more to assist you in upgrading your cloud career. Subscribe to get them all!