avatarTech Notes

Summary

The web content explains how to create persistent aliases in a Dockerfile for an Ubuntu image by modifying the .bashrc file, ensuring that the aliases are available in every new shell instance within the Docker container.

Abstract

The article titled "Make an alias with Dockerfile for Ubuntu image" addresses a common issue faced by users when their aliases, set using the RUN command in a Dockerfile, do not persist. It clarifies that this occurs because each RUN command invokes a new shell instance, which does not retain previous session aliases. The solution provided involves appending the desired aliases to the .bashrc file within the Dockerfile, which is executed for interactive shells. This ensures that aliases, such as alias dir='ls -halp', are loaded each time a new shell is started. The article also references a Stack Overflow discussion that further elaborates on setting Bash aliases in Docker containers.

Opinions

  • The author implies that setting aliases directly in the Dockerfile with the RUN command is insufficient for persistence across shell instances.
  • It is suggested that modifying the .bashrc file is a standard approach for making aliases sticky in Docker containers.
  • The author expresses a personal preference for adding an alias for the ls command to provide a more detailed view by default.
  • The use of stream operators (>>) to append aliases to the .bashrc file is recommended as a best practice within the Dockerfile context.

Make an alias with Dockerfile for Ubuntu image

Why aren’t my aliases sticky? ;_;

You cannot just simply set an alias in your Dockerfile:

# syntax=docker/dockerfile:1
FROM ubuntu:18.04
RUN alias dir='ls -halp'

They don’t stick. You might be wondering why, since you seem to be able to use the RUN command to easily run “apt-get” and other command line tools, and those apt-get installs don’t disappear, so how come my alias is disappearing? It is disappearing because when you call RUN you are opening a new shell instance. You need to set your bashrc file with the alias you want so that each shell instance will initialize your alias on startup.

You need to add it to a bashrc file. This will only apply to interactive terminals. [1]

RUN echo 'alias hi="echo hello"' >> ~/.bashrc

This will set an alias so that when you type “hi” into the terminal, it will echo “hello” back to you.

The >> is a stream operator, so you are streaming the string inside the single quotes into the text file at ~/.bashrc.

I am fond of always adding this one to all my Dockerfiles:

RUN echo 'alias ls="ls -halp"' >> ~/.bashrc

so that when I run ls I can get a more detailed view.

References

[1] How can I set Bash aliases for docker containers in Dockerfile? https://stackoverflow.com/questions/36388465/how-can-i-set-bash-aliases-for-docker-containers-in-dockerfile

Dockerfiles
Alias
Bashrc
Ubuntu
Image
Recommended from ReadMedium