PostgreSQL Flake

Hey,

I was wondering how I could create a devShell using a flake, for developing my database using postgreSQL.

Currently I have the following flake setup:

{
  description = "Nix flake for postgresql environment.";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixos-25.05";
  };

  outputs = { self, nixpkgs, ... }:
  let
    system = "x86_64-linux";
  in {
    devShells."${system}".default =
    let
      pkgs = import nixpkgs { inherit system; };
    in pkgs.mkShell {
      packages = with pkgs; [
        postgresql
      ];

      shellHook = ''
        postgres --version
      '';
    };
  };
}

I then initialised my database with init -D data.

But when I run pg_ctl -D data -l logfile start I have an issue from within the logfile:

2025-10-09 14:13:44.668 BST [304481] FATAL:  could not create lock file "/run/postgresql/.s.PGSQL.5432.lock": No such file or directory

Now, I understand that NixOS doesn’t have a /run/ directory, and that postgreSQL is trying to setup its port number as 5432. Is there a way that I could do this within the flake.nix file using devShells? Or is it not possible to do so, since it is interacting with the system?

Correction: NixOS does have /run. Thanks @emmanuelrosa

NixOS does have /run, but for running postresql under your own user account you can use an alternative directory for the lock file using the -k option. When using pg_ctl you may need to use the -o- option: pg_ctl -D data -L logfile -o "-k /path/to/fake/run" start

I have something similar, but it just uses a BASH shell built with Nix, rather than a devShell. See quickdb/pkgs/postgresql/default.nix at cdef26108fb9c58330681150942b777e23ad165b · emmanuelrosa/quickdb · GitHub

1 Like

If you use nix-shell or nix develop, Nix will run shellHook in that environment. Your issue is probably just that the directory for the socket file does not exist.

You could try to create and chmod it into the shellHook but that might break on systems that have global PostgreSQL instance so you might be better off using an ad-hoc directory as Emmanuel suggested.

I have something similar in Python:

Also, there is Domen’s excellent devenv, which supports many more services:

2 Likes