How to Set Up Local Yum Repositories on CentOS 7
In Linux, a repository is a central database of software. Linux distributions have a central repository for system and commonly-used software.
Often administrators may have a need for a specialized software package, or to manage network bandwidth. For these reasons, they need to set up a new custom local repository.
Yum is a local repository for RPM package files. These packages compress available software for Linux distributions. With the repository, you can download, install and hold packages on a local disk or remotely.
This tutorial walks you through setting up a local Yum repository on CentOS 7.
- Access to a user account with root or sudo privileges
- Access to a terminal window/command-line (Menu > Applications > Utilities > Terminal)
- The YUM (Yellowdog Updater Modified) package manager, installed by default
Set Up and Configure Yum Repositories on CentOS
Step 1: Configure Network Access
Firstly, hosting a yum repository requires you to configure the system for network access.
Yum typically delivers files over either FTP or HTTP. However, you cannot configure for both, so take a moment to decide which method you would like to use.
If you already have the system configured as a web server with Apache or an FTP server with vsftpd, skip to Step 2.
To use HTTP, install the Apache web services package with the command:
If you are using FTP instead, install the vsftpd software package with:
This is an example of an output with the latest version already installed:
Note: Instead of Apache, you can also use Nginx as a web server. Before doing so, make sure you open the correct ports on your firewall (Port 80 for HTTP, Port 21 for FTP).
Step 2: Create Yum Local Repository
One helpful tool is the createrepo software package. This software bundles several .rpm files together into a repomd repository. Install the software by entering the following:
Next, install yum-utils to give your system a better toolbox for managing repositories. Install yum-utils by entering the following:
This is an example of a possible output:
Step 3: Create a Directory to Store the Repositories
Then, create a directory for an HTTP repository using:
Alternaticreate an FTP directory by typing the following:
Step 4: Synchronize HTTP Repositories
Download a local copy of the official CentOS repositories to your server. This allows systems on the same network to install updates more efficiently.
To download the repositories, use the commands:
The system should reach out and download copies of the official repositories.
In the previous commands, the options are as follows:
- –g – lets you remove or uninstall packages on CentOS that fail a GPG check
- –l – yum plugin support
- –d – lets you delete local packages that no longer exist in the repository
- –m – lets you download comps.xml files, useful for bundling groups of packages by function
- ––repoid – specify repository ID
- ––newest-only – only download the latest package version, helps manage the size of the repository
- ––download-metadata – download non-default metadata
- ––download-path – specifies the location to save the packages
If you’re using FTP, substitute your FTP directory in the commands above. You can also use your installation CD as a source for repositories.
First, mount the cd, then copy the files into your FTP directory with the following:
Step 5: Create the New Repository
We’ll use the createrepo utility to create a repository.
To create the repository for HTTP use the command:
The terminal will display the following information:
Similarly, create a repository for FTP, enter the following:
Step 6: Setup Local Yum Repository on Client System
Now set up a local Yum Repository on a clients machine.
1. First, switch to the client system and login as a user with root or sudo privileges.
2. Next, you’ll need to prevent yum from downloading from the wrong location. To do this, move the default yum repository files with the following command:
This command stores the files in the /tmp/ directory. You can substitute any other location you’d like.
3. Create and edit a new config file:
The system should open a new file in a text editor.
4. In the new file, enter the command (replacing the IP address with the IP address of your server):
5. Finally, save the file and exit.
If you’re configuring for FTP, use the following instead (replacing the IP address with the IP address of your server):
Step 7: Test the Configuration
While still on the client system, run a command to install a package with the yum package manager:
The system should accordingly reach out to your server and install the software.
After following these steps, you now know how to set up a local YUM repository on CentOS 7.
In addition to downloading the default repositories (or copying them from the CD), you can also copy any other software packages into your storage folder. This provides a simple and central location that users can access and install software.
Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7a2558b91dfa77a9 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Create Local Repos
If you have downloaded, created, or rebuilt RPM packages locally (as explained in TipsAndTricks/YumAndRPM «Get set up for rebuilding packages while not being root») you may want a place to put them so they are accessible from all the machines on your local net.
Note: For a single package or a stand-alone end-user system, don’t go through all the overhead of building a formal NFS export and package repository — just use either:
or the older and simpler approach for an unsigned package:
One benefit of the rpm based approach, is that a developer can incrementally solve dependencies, and rpm will suggest what the next needed package must provide, and one can build up a ‘just enough’ solution:
Use of a yum repo adds additional benefits, as yum can resolve dependencies and automatically satisfy them from available repositories.
- The example will cover i386 for CentOS4. A similar approach can be followed for other architectures and versions. One can also use other means of providing access to the repo, such as a HTTPd and/or an FTP server. Convention on command-line sections: # means run as root, $ means run as a user — builduser in the example.
- First create directory structure on the server, say server1:
- If createrepo is not already installed, as it will not be by default, install it.
- Build a spiffy new set of packages from foo-1.2.3.4-1.el4.src.rpm (or alternately get packages from another trusted source). This creates (for example)
- Move the files to the repo and create metadata:
- Note: Steps 3 and 4 are repeated as new packages are added to the repo.
- For HTTP or FTP repos the baseurl line must be changed accordingly.
Repeat the last three steps for additional clients as required.
This page created and maintained by PhilSchaffner. Other Wiki contributors are invited to make corrections, additions, or modifications.
HowTos/CreateLocalRepos (последним исправлял пользователь анонимно 2019-12-09 09:11:37)
Подключение EPEL, RPMForge и других репозиториев в CentOS
В одной из статей уже рассматривалось использование пакетного менеджера Yum в операционной системе CentOS. Сейчас же разберемся с репозиториями, которые являются неотъемлемой частью инфраструктуры управления пакетами.
Репозиторий представляет собой централизованное хранилище скомпилированных и готовых к установке программ с метаданными об их совместимости и взаимозависимостях. Репозитории бывают:
- официальные — поддерживаемые разработчиками дистрибутива ОС. Содержат пакеты, являющиеся частью операционной системы, а также дополнительные программы, тесно в нее интегрированные;
- коммерческие — поддерживаемые разработчиками стороннего платного программного обеспечения. Доступ к таким репозиториям обычно требует наличия подписки;
- открытые — поддерживаемые энтузиастами, сообществом или разработчиками свободно-распространяемого ПО. Открыты для всех желающих.
Так как перечень программного обеспечения, включенного в состав операционной системы ограничен, и разработчики не всегда успевают вовремя тестировать и включать в свои репозитории свежие версии сторонних проектов (веб-серверы, почтовые серверы, СУБД и т.д.), зачастую приходится подключать дополнительные репозитории.
Есть два основных способа подключения. Наиболее предпочтительный — установка RPM-пакета репозитория. В ходе этой операции скачиваются и создаются все необходимые файлы, после чего новый репозиторий появится в списке подключенных (команда yum repolist). Другой способ — создать файл настроек репозитория самостоятельно в каталоге /etc/yum.repos.d/. Файл должен иметь расширение repo и содержать следующие параметры:
[repo]
name=repo_name
baseurl=repo_url[repo] — краткое имя репозитория;
name — полное имя репозитория;
baseurl — ссылка на репозиторий (может быть заменена параметром mirrorlist или metalink — ссылка на список региональных зеркал репозитория);
gpgcheck — проводить ли проверку цифровой подписи пакетов (если значение параметра 1 — проводить, если 0 — не проводить);
gpgkey — местоположение открытого ключа репозитория, с помощью которого производится проверка подписи;
enabled — используется ли репозиторий при поиске и установке пакетов (1 — используется, 0 — репозиторий отключен).Все необходимые значения для указанных параметров обычно можно найти на веб-сайте соответствующего репозитория.
Подключаем сторонний репозиторий
Если говорить о дистрибутивах, основанных на Red Hat Linux, самым популярным репозиторием, рекомендуемым для подключения, является Extra Packages for Enterprise Linux (EPEL). На CentOS-серверах, развернутых из наших шаблонов, этот репозиторий уже подключен. В случае, если операционная система установлена с нуля, подключить EPEL достаточно просто:
yum install epel-release
RPM-пакет с настройками EPEL уже содержится в составе официального репозитория CentOS, поэтому все необходимые файлы и GPG-ключи загрузятся автоматически. Если просмотреть содержимое файла /etc/yum.repos.d/epel.repo, то мы увидим уже знакомые параметры:
Скриншот №1. Параметры файла
Другой распространенный репозитарий — Remi`s RPM repository, содержащий актуальные версии пакетов PHP-стека. Репозиторий EPEL должен быть подключен в ОС, так как пакеты Remi зависят от пакетов репозитория EPEL. Детальную информацию можно найти на сайте https://rpms.remirepo.net/. Для подключения достаточно скачать RPM-пакет и запустить его установку:
wget https://rpms.remirepo.net/enterprise/remi-release-7.rpm
rpm -Uvh remi-release-7.rpmЗапустим yum repolist и убедимся, что репозитории зарегистрированы в операционной системе:
Скриншот №2. Yum repolist
По умолчанию включен только репозиторий remi-safe — он содержит пакеты, не замещающие пакеты дистрибутива операционной системы, чем минимизируются возможные конфликты и проблемы в работе. Если посмотреть список REPO-файлов, которые появились, увидим достаточно большой перечень:
Скриншот №3. Список REPO-файлов
Эти репозитории отключены и должны включаться администратором сервера в тех случаях, когда это требуется. Чтобы включить репозиторий на постоянной основе, устанавливаем параметр enabled=1 в соответствующем REPO-файле. Для разовых операций используем параметр —enablerepo=repo_name в соответствующей команде yum, например:
yum —enablerepo=remi install php
Одним из широко распространенных ранее сторонних репозиториев был RepoForge (RPMForge), но, к сожалению, на данный момент он уже не поддерживается. Хотя физически репозиторий доступен, пакеты в нем уже давно не обновляются, в связи с чем использовать его не рекомендуется. Если все же по каким-то причинам требуется им воспользоваться, подключить его тоже достаточно просто — на странице http://repoforge.org/use/ находим ссылку на требуемую версию, скачиваем пакет и устанавливаем. Например, для CentOS 7:
wget http://repository.it4i.cz/mirrors/repoforge/redhat/el7/en/x86_64/rpmforge/RPMS/rpmforge-release-0.5.3-1.el7.rf.x86_64.rpm
yum localinstall rpmforge-release-0.5.3-1.el7.rf.x86_64.rpmСкриншот №4. Версия для CentOS 7