Search code examples
amazon-web-servicesdockeramazon-ecsaws-fargate

Next JS serverless deployment on AWS ECS/Fargate: environment variable issue


so my goal is to deploy a serverless Dockerized NextJS application on ECS/Fargate. So when I docker build my project using the command docker build . -f development.Dockerfile --no-cache -t myapp:latest everything is running successfully except Docker build doesn't consider the env file in my project's root directory. Once build finishes, I push the Docker image to Elastic Container Repository(ECR) and my Elastic Container Service(ECS) references that ECR.

So naturally, my built image doesn't have a ENV file(contains the API keys and DB credentials), and as a result my app is deployed but all of the services relying on those credentials are failing because there isn't an ENV file in my container and all of the variables become undefined or null.

To fix this issue I looked at this AWS doc and implemented a solution that stores my .env file in AWS S3 and that S3 ARN gets refrenced in the container service where the .env file is stored. However, that didn't workout and I think it's because of the way I'm setting my next.config.js to reference my environmental files in my local codebase. I also tried to set my environmental variables manually(very unsecure, screenshot below) when configuring the container in my task defination, and that didn't work either.

My next.confg.js

const dotEnvConfig = { path: `../../${process.env.NODE_ENV}.env` };

require("dotenv").config(dotEnvConfig);

module.exports = {
  serverRuntimeConfig: {
    // Will only be available on the server side
    xyzKey: process.env.xyzSecretKey || "",
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    appUrl: process.env.app_url || "",
  },
};

So on my local codebase in the root directory I have two files development.env (local api keys) and production.env(live api keys) and my next.config.js is located in /packages/app/next.config.js

enter image description here


Solution

  • So apparently it was just a plain NextJS's way of handling env variables.

    In next.config.js

    module.exports = {
      env: {
        user: process.env.SQL_USER || "",
    // add all the env var here
      },
    
    };
    

    and to call the environmental variable user in the app all you have to do is call process.env.user and user will reference process.env.SQL_USER in my local .env file where it will be stored as SQL_USER="abc_user"