Alpine linux создать пользователя

How do I add a user when I’m using Alpine as a base image?

I’m using alpine (or an image that is based on Alpine) as the base image in my Dockerfile. Which instructions do I need to add to create a user? Eventually I’ll use this user to run the application I’ll place into the container so that the root user does not.

3 Answers 3

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup ).

FROM alpine:latest # Create a group and user RUN addgroup -S appgroup && adduser -S appuser -G appgroup # Tell docker that all future commands should run as the appuser user USER appuser 

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)

Or alternatively, you can replace the whole snippet above using this: USER 405 which is the guest user within Alpine Linux.

Читайте также:  Все об операционной системе linux ubuntu

I’d go with creating a new user because I want that user to have the same UID/GID as the one on the host OS, so that there’s no permission issue when running docker in Linux. (not an issue with macOS/Windows users)

Note that since Alpine is based on BusyBox, its adduser and addgroup commands are different from adduser and addgroup as provided by Debian and Ubuntu which in turn are front ends to useradd and groupadd . Notably, the Debian and Ubuntu commands only support long form options. See: manpages.debian.org/stretch/adduser/adduser.8.en.html

The commands are adduser and addgroup .

Here’s a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):

ENV USER=docker ENV UID=12345 ENV GID=23456 RUN adduser \ --disabled-password \ --gecos "" \ --home "$(pwd)" \ --ingroup "$USER" \ --no-create-home \ --uid "$UID" \ "$USER" 
  • —disabled-password prevents prompt for a password
  • —gecos «» circumvents the prompt for «Full Name» etc. on Debian-based systems
  • —home «$(pwd)» sets the user’s home to the WORKDIR. You may not want this.
  • —no-create-home prevents cruft getting copied into the directory from /etc/skel

The usage description for these applications is missing the long flags present in the code for adduser and addgroup.

The following long-form flags should work both in alpine as well as debian-derivatives:

adduser

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary. Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP --home DIR Home directory --gecos GECOS GECOS field --shell SHELL Login shell --ingroup GRP Group (by name) --system Create a system user --disabled-password Don't assign a password --no-create-home Don't create home directory --uid UID User id 

One thing to note is that if —ingroup isn’t set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.

addgroup

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary. Usage: addgroup [-g GID] [-S] [USER] GROUP Add a group or add a user to a group --gid GID Group id --system Create a system group 

I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.

Читайте также:  Linux source list ubuntu

The intent is to prepend that script as the first argument to ENTRYPOINT which should cause Docker to infer UID and GID from a relevant bind mount.

An environment variable «TEMPLATE» may be required to determine where the permissions should be inferred from.

(At the time of writing I don’t have documentation for my script. It’s still on the todo list!!)

Источник

👥 Как добавлять и удалять пользователей в Alpine Linux

Alpine Linux – это многозадачная и многопользовательская облегченная операционная система.

Известна как автономная ОС или для контейнерных систем Linux, таких как Docker, LXD и другие.

Мы можем создать пользователя для разных задач.

Например, пользователь www для статических веб-страниц и другой пользователь для управления системой.

В любом случае, добавление и удаление пользователей является важной задачей для разработчиков и системных администраторов.

В этом руководстве объясняется, как добавлять и удалять пользователей в Alpine Linux.

Как добавить пользователя в Alpine Linux

Чтобы создать новую учетную запись пользователя в Alpine, используйте команду adduser.

Синтаксис следующий для добавления пользователя в Alpine:

Давайте создадим новую учетную запись пользователя с именем wendy с помощью команды adduser, введите:

Пример вывода: Changing password for wendy New password: Retype password: passwd: password for wendy changed by root
drwxr-sr-x 2 wendy wendy 2 May 2 21:20 /home/wendy

Alpine Linux использует файл /etc/passwd для хранения всех имен пользователей и зашифрованных паролей, хранящихся в файле /etc/shadow.

Не создавать домашний каталог

Вы можете указать adduser не создавать домашний каталог, передав опцию -H:

Мы также можем установить путь к домашней директории (по умолчанию это /home/$USER/), передав опцию -h /path/to/home/dir

Вход в шелл

По умолчанию /bin/bash установлен как оболочка для входа для всех новых пользователей и /bin/sh для системных пользователей.

Читайте также:  Удалить intellij idea linux

На большинстве систем я устанавливаю и использую bash.

Итак, мы собираемся установить /bin/bash (или любую другую оболочку из файла /etc/shells) в качестве оболочки для входа:

# adduser -h /efs/home/wendy -s /bin/bash wendy

Наконец, используйте команду id или напрямую запросите файл /etc/passwd с помощью команды grep, чтобы убедиться, что учетная запись пользователя создана в Alpine Linux:

Как удалить пользователя

Иногда нам не нужна учетная запись пользователя, и мы можем удалить их из CLI.

Удаляем учетную запись пользователя из командной строки

Чтобы удалить пользователей на Alpine, используйте команду deluser.

itisgood
🛠️ Как исправить “_get_comp_words_by_ref: command not found”
Что изменилось в вопросе продвижения сайта за последние 5 лет?

You may also like

🐧 Сравнение команд Printf и Echo на Linux

🐧 Что означает -z на Bash

🐧 Примеры команд size на Linux

🐧 Linux_Logo – вывод ASCII логотипа Linux с.

🐧 Параметры конфигурационного файла Apt /etc/apt/apt.conf

🐧 Разница между выключением, перезагрузкой и остановкой Linux

⌨️ Введение в команду “./configure”: Компиляция исходного кода.

🐧 Что такое /dev/zero на Linux?

Каковы лучшие дистрибутивы Linux в 2022 году

🐧 Работа с переменной PATH на Linux. Это.

Leave a Comment Cancel Reply

• Свежие записи

• Категории

• Теги

• itsecforu.ru

• Страны посетителей

IT is good

В этой статье вы узнаете, как удалить удаленный Git-репозиторий. Процесс прост, но его полезно запомнить, чтобы избежать неожиданностей в будущем. Git – это…

В 11-й версии своей операционной системы Microsoft серьезно переработала интерфейс и убрала несколько привычных функций. Нововведения не всем пришлись по душе. Мы дадим…

Продажа ноутбука нередко становится хлопотным занятием. Кроме поиска покупателя, продавцу необходимо подготовить устройство перед проведением сделки. Но если последовательно выполнить все шаги, ничего…

Вы можете оказаться в ситуации, когда вам нужно использовать скрипт шелла для чтения файлов построчно. В этом руководстве я расскажу о нескольких способах…

Вторичное жильё выгоднее для молодых семей, желающих приобрести свою первую квартиру. Сталкиваясь с ипотечным кредитованием, можно избежать много лишней суеты и проблем, если…

Источник

Оцените статью
Adblock
detector