Run databases in nix-shell developer environments

Hello,
I was wondering how I could start a database in the background with nix-shell for my program to interact with it

The idea is that I don’t have to always run it in the background but instead only when I’m developing on my project; and to really make my developer environment 100% pure.

What I have so far (all ideas) is that I start e.g. mongod in my shellHook but I cannot think of a way to stop it when I exit my shell.

Would my idea even work? Anything else that could pose problems?

Any thoughts and help would be appreciated :slight_smile:

4 Likes

There is this SE answer about using bash trap statement to stop the database.

1 Like

What @ilkecan mentioned definitely works, and I’m using it in my dev shell.nix (extensively commented) that drops me in a shell with Erlang, Elixir, and Phoenix available, and a PostgreSQL instance is humming in the background. Exiting the shell will clean up everything using trap. You can also try it out with

nix-shell -v -E 'import (builtins.fetchurl "https://raw.githubusercontent.com/toraritte/shell.nixes/main/elixir-phoenix-postgres/shell.nix")'

The README may also contain some extra info.

1 Like

This sounds like shopify’s use case.

IIRC, they exported an ‘up’ and ‘down’ command as part of the shell. These would in turn start and stop launchd user services. You could probably do something similar.

blog: What Is Nix — Developer Tooling (2021)
video: Nix-based development environments at Shopify (NixCon 2019) - YouTube

2 Likes

Thanks for the help guys! I’ve settled with this: lila/shell.nix at nix · legendofmiracles/lila · GitHub it starts both redis and mongod in the background (if it isn’t running already), and only kills it when no other shell is open.

2 Likes