How to Run PowerShell Script on Linux Docker Container Stopping: A Complete Guide [2026]

run powershell script on linux docker container stopping

Running PowerShell scripts inside Linux Docker containers might sound a bit unusual at first, especially if you come from a traditional Windows background where PowerShell has always been the go-to automation tool. However, with the rise of PowerShell Core, Microsoft’s open-source, cross-platform version of PowerShell, it is now entirely possible to run PowerShell on Linux systems—including inside Docker containers.

This opens up exciting possibilities for DevOps engineers, system administrators, and developers who are already comfortable with PowerShell but want to take advantage of the flexibility and scalability that Linux containers provide. One of the most practical use cases is being able to run PowerShell script on Linux Docker container stopping, which allows you to execute important cleanup, logging, or notification tasks automatically when a container receives a stop signal.

Think about real-world scenarios:

  • You may want to remove temporary cache files before the container shuts down.
  • You might need to log container shutdown events into a centralized log file or monitoring system for auditing purposes.
  • In more advanced setups, you could even trigger API calls or notifications to alert other services that a container is being terminated.

Instead of manually handling these shutdown processes, you can automate them with a PowerShell script inside your Linux Docker container. By leveraging Docker’s lifecycle hooks and Linux signal trapping, you gain fine-grained control over what happens during container shutdown, ensuring your application remains consistent, reliable, and production-ready.

In this step-by-step guide, we’ll break down exactly how to achieve this: from setting up PowerShell Core in a Linux container, to creating lifecycle hooks, to writing practical PowerShell scripts that run whenever the container stops. By the end, you’ll have a repeatable method to run PowerShell script on Linux Docker container stopping—something that can be applied to real-world DevOps pipelines, cloud-native applications, and containerized microservices.


Why Run PowerShell Scripts on Linux Docker Containers?

Traditionally, PowerShell was tied to Windows systems, and many developers associated it only with Windows Server automation or desktop scripting. But times have changed. With the release of PowerShell Core, Microsoft made PowerShell a cross-platform tool, now running smoothly on Linux, macOS, and Windows. This shift means that if you already know PowerShell from your Windows experience, you can now apply the same familiar scripting techniques in Linux environments, including inside Docker containers.

So why does this matter for Docker users? Let’s think about the lifecycle of a Docker container. A container is not just about starting up—it also shuts down, and that moment is just as critical as startup. When a container stops, you may need to run maintenance scripts or cleanup tasks to ensure your application remains stable and predictable.

Here are a few real-world examples of what you might want to automate when a container is stopping:

  • 🧹 Removing temporary files: Containers often generate temporary data or cache files. If you don’t clean them up properly, they may bloat storage or cause inconsistent behavior in future runs.
  • 📝 Logging container shutdown events: In production, it’s important to know exactly when and why a container stopped. Logging this event with a timestamp makes troubleshooting much easier.
  • 📡 Notifying external systems before shutdown: Sometimes your container needs to tell another service (like a monitoring system or load balancer) that it’s going offline. Automating this step ensures smooth orchestration.

And this is exactly where our main topic comes in: running a PowerShell script on Linux Docker container stopping. Instead of leaving shutdown tasks to manual scripts or external monitoring, you can directly embed the logic into your container.

In this tutorial-style guide, we’ll walk step by step through:

  1. Installing PowerShell Core in a Linux Docker container
  2. Using Docker lifecycle hooks and Linux signal traps to catch the stop event
  3. Writing a PowerShell script that automatically runs when the container is stopping
  4. Testing with real-world scenarios like logging shutdowns or cleaning up files

By the end of this walkthrough, you won’t just know that it’s possible to run PowerShell scripts in Linux containers—you’ll have a working setup that you can adapt to your own applications and DevOps workflows.


Prerequisites

Before we dive into the actual steps to run PowerShell script on Linux Docker container stopping, let’s make sure you have the necessary tools and setup ready. Think of this as your preparation checklist.

1. Docker Installed on Your Linux Host

You’ll need Docker installed on your Linux machine since containers are the foundation of this tutorial. If Docker isn’t already installed, you can do so with the following commands (on Ubuntu/Debian-based systems):

sudo apt-get update
sudo apt-get install docker.io -y
sudo systemctl start docker
sudo systemctl enable docker

To verify installation:

docker --version

If you see a version number, Docker is ready to go.


2. PowerShell Core Installed Inside the Container

Unlike the old Windows-only PowerShell, PowerShell Core (pwsh) works seamlessly inside Linux containers. This is essential because our goal is to run a PowerShell script when a Linux Docker container is stopping.

To add PowerShell Core inside your container, you’ll use a Dockerfile. Here’s a simple example:

# Use Microsoft’s official PowerShell base image
FROM mcr.microsoft.com/powershell:latest  

# Set working directory
WORKDIR /app  

# Copy your PowerShell script into the container
COPY myscript.ps1 /app/myscript.ps1  

# Default command
CMD ["pwsh"]

This ensures that whenever your container runs, PowerShell is available.


3. Basic Knowledge of Dockerfile and Linux Shell Scripting

Since we’ll be combining Docker lifecycle hooks, Linux shell scripting, and PowerShell scripts, it’s helpful if you have at least a beginner-level understanding of:

  • Writing a Dockerfile (to define your container environment).
  • Creating simple Bash scripts (to trap signals like SIGTERM).
  • Running and stopping Docker containers from the command line.

Don’t worry if you’re not an expert—you’ll learn most of the process step by step in this tutorial.


✅ With these prerequisites in place, you’re now fully prepared to move on to the next step: understanding how Docker container lifecycle hooks work and how we can tie them to a PowerShell script when the container stops.


Understanding Docker Container Lifecycle Hooks

Every Docker container has a lifecycle: it starts, runs, and eventually stops. During these stages, Docker provides special hooks that let you control what happens inside the container. The most common lifecycle hooks are:

  • ENTRYPOINT – Defines the main process that runs when the container starts.
  • CMD – Provides default arguments for the container’s process.
  • Signals (like SIGTERM) – Sent by Docker when you run commands such as docker stop.

When a container is stopped, Docker doesn’t just shut it down immediately—it sends a SIGTERM signal to the main process inside the container. This gives the process a chance to clean up before it exits.

👉 And this is the key to our solution. If we want to run a PowerShell script on Linux Docker container stopping, we need to catch this SIGTERM signal and then trigger our script.

The typical approach is to use a small shell script as the container’s entrypoint. Inside that script, you can set up a trap for the SIGTERM signal. When Docker sends the stop signal, the trap will run, and from there you can invoke your PowerShell script.

This way, instead of the container just shutting down silently, you gain full control over what happens in the last moments of its lifecycle—whether that’s logging, cleanup, or notifying another service.

Here’s a practical example:

#!/bin/bash
# trap.sh
trap 'pwsh /app/myscript.ps1' SIGTERM

echo "Container is running..."
while true; do
    sleep 1
done

And update your Dockerfile:

COPY trap.sh /app/trap.sh
RUN chmod +x /app/trap.sh
ENTRYPOINT ["/app/trap.sh"]

Now, whenever the container receives a stop signal, it will execute myscript.ps1 before shutting down.


Real-World Example: Logging Container Shutdown

Suppose you want to log the shutdown timestamp to a file using PowerShell:

# myscript.ps1
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path "/app/container_shutdown.log" -Value "Container stopped at $timestamp"

When you stop the container:

docker stop my-container

The myscript.ps1 will automatically run, appending the shutdown time to your log file. This is particularly useful in production environments where container shutdown events must be tracked.


Best Practices for Running PowerShell Scripts on Linux Docker Container Stopping

Now that you know how to hook into the container shutdown process, it’s important to follow some best practices. These will make your setup more reliable, easier to maintain, and production-ready. Let’s go through them one by one.


1. Always Use pwsh for PowerShell Core on Linux Containers

On Linux, the traditional powershell.exe command doesn’t exist—it’s replaced by PowerShell Core, which is invoked using the pwsh command. This ensures your scripts are executed properly across different platforms.

For example, instead of:

powershell myscript.ps1

You should always use:

pwsh /app/myscript.ps1

This guarantees that your script runs smoothly inside Linux containers without compatibility issues.


2. Test Your Trap Scripts Locally Before Production

Signal handling can behave differently depending on the base image, entrypoint setup, or container orchestration (like Docker vs. Kubernetes). Before deploying your container to production, test your trap logic locally by running and stopping the container multiple times.

Example test:

docker run --name test-container myimage
docker stop test-container

Check if your PowerShell script executed correctly. If it logs to a file, verify that the log was updated. This prevents surprises when you scale up in production.


3. Keep Your PowerShell Scripts Idempotent

When Docker stops a container, it may send multiple stop signals (like SIGTERM followed by SIGKILL if the container doesn’t stop in time). This means your shutdown script might run more than once.

To avoid problems, make your scripts idempotent—meaning running them multiple times should not cause errors or duplicate work.

For example, instead of appending the same shutdown log entry twice, you could check if the log already contains the entry before writing again. Or if you’re deleting temporary files, use Remove-Item -ErrorAction SilentlyContinue so the script doesn’t break if the file is already gone.


4. Use Minimal Base Images for Efficiency

Containers should be lightweight and fast. While it’s tempting to use a large image like Ubuntu with lots of preinstalled tools, it’s better to choose a minimal base image that includes only what you need.

For PowerShell, Microsoft provides official images like:

FROM mcr.microsoft.com/powershell:latest

This keeps your container small but fully compatible with PowerShell Core. Smaller images mean faster builds, quicker deployments, and reduced security risks.


✅ By following these best practices, you’ll ensure your PowerShell scripts inside Linux Docker containers run reliably and predictably every time a container stops—whether you’re cleaning up, logging, or notifying external systems.


Conclusion

At first glance, the idea of running a PowerShell script on Linux Docker container stopping might sound complicated or even counterintuitive. After all, PowerShell has its roots in Windows, while Docker is heavily associated with Linux-based workloads. But thanks to PowerShell Core’s cross-platform capabilities and Docker’s flexible lifecycle hooks, this combination is not only possible—it’s practical and powerful.

When you look deeper, the real value here isn’t just about making a script run at shutdown. It’s about treating containers as first-class citizens in your automation workflow. A container doesn’t simply exist in isolation—it communicates with other services, writes temporary data, and plays a role in a larger system. By adding a simple PowerShell script at shutdown, you give your container the ability to:

  • Exit gracefully by cleaning up after itself.
  • Leave behind an audit trail with clear shutdown logs.
  • Notify other systems that it’s going offline, ensuring better orchestration.

This approach makes your applications more predictable, more resilient, and easier to maintain in production environments.

If you think about it, this is also a great example of how DevOps is evolving. Ten years ago, few developers imagined running PowerShell scripts inside Linux environments. Today, with cross-platform tools, hybrid infrastructures, and container-based deployments, the barriers between “Windows” and “Linux” skills are dissolving. What matters is choosing the right tool for the right moment—and in many cases, PowerShell remains a powerful ally.

So, the next time you deploy containers, don’t overlook what happens when they stop. Startup scripts are common, but shutdown automation is just as important for building reliable, production-grade systems. Start by writing a small trap script, integrate your PowerShell shutdown logic, and test it locally. Once you push it into production, you’ll see the difference in how cleanly and reliably your containers behave.

In short: running a PowerShell script on Linux Docker container stopping isn’t just a neat trick—it’s a mindset shift toward cross-platform automation, graceful lifecycle management, and proactive DevOps practices.


Frequently Asked Questions (FAQs)

1. Can I run PowerShell scripts inside Linux Docker containers?

Yes. Thanks to PowerShell Core (pwsh), you can run PowerShell scripts inside Linux containers just like you would on Windows.


2. How do I run a PowerShell script when a Docker container stops?

You need to trap the SIGTERM signal inside a shell script and then call your PowerShell script from there. This ensures the script runs during container shutdown.


3. Why do I need to trap the SIGTERM signal?

When you run docker stop, Docker sends a SIGTERM signal to give the container a chance to exit gracefully. By trapping this signal, you can execute cleanup or logging scripts before the container shuts down.


4. Should I use powershell or pwsh inside Linux containers?

Always use pwsh, which is the command for PowerShell Core. The powershell command exists only on Windows.


5. What are real-world use cases for running PowerShell script on Linux Docker container stopping?

Common scenarios include:

Cleaning up temporary files
Writing shutdown logs
Notifying monitoring systems
Updating databases or API endpoints before shutdown


6. Can I run multiple PowerShell scripts on container stop?

Yes. You can chain multiple scripts inside your trap script, or have one main PowerShell script that calls other scripts.


7. How do I test if my PowerShell script runs on container shutdown?

Run your container, then stop it with:

docker run --name test myimage
docker stop test

Check your logs or output file to confirm the script executed.


8. What happens if the script takes too long to run?

Docker gives containers a grace period (default 10 seconds) after sending SIGTERM. If your script takes longer, Docker will forcefully kill the container with SIGKILL. You can extend this timeout using:

docker stop -t 30 mycontainer


9. Does this work in Kubernetes too?

Yes. Kubernetes also sends SIGTERM to containers before termination. You can use the same approach to run PowerShell scripts on pod shutdown.


10. What are the best practices for PowerShell scripts in Docker shutdown?

Always use pwsh for Linux containers.
Test scripts locally before production.
Keep scripts idempotent (safe to run multiple times).
Use minimal base images for efficiency.

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *


Share via
Copy link